如何获得布局坐标?

时间:2015-12-16 19:10:41

标签: android

我在一个布局中有两个布局。我想获得GirdLayout坐标。我已经尝试了gridLayout.getTop()等等,但是所有这些都返回0,即使网格几乎位于中心位置。我怎样才能获得GridLayout个协调员?

XML:

 <LinearLayout>
    <LinearLayout>...</LinearLayout>
    <GridLayout>…</GridLayout>
</LinearLayout>

编辑:

活动代码:

public class LoginActivity extends Activity {

    GridLayout gridLayout;
    LinearLayout linearLayout, generalLayout;

    int lTop, lBottom, lRight, lLeft;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_layout);

        gridLayout = (GridLayout) findViewById(R.id.gridLayout);
        linearLayout = (LinearLayout) findViewById(R.id.imageLayout);
        generalLayout = (LinearLayout) findViewById(R.id.generalLayout);

        lTop = gridLayout.getTop();
        lBottom = gridLayout.getBottom();
        lRight = gridLayout.getRight();
        lLeft = gridLayout.getLeft();
    }
}

2 个答案:

答案 0 :(得分:1)

试试这个:

Rect r = new Rect();
gridLayout.getWindowVisibleDisplayFrame(r);  
int x = r.centerX();
int y = r.centerY();

答案 1 :(得分:0)

尝试做你的&#34;顶级获取&#34;在活动开始后,用户可以通过将此逻辑移动到活动的onStart覆盖,如此,

编辑:也尝试使用getX(),getY()代替。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login_layout);
    gridLayout = (GridLayout) findViewById(R.id.gridLayout);
    linearLayout = (LinearLayout) findViewById(R.id.imageLayout);
    generalLayout = (LinearLayout) findViewById(R.id.generalLayout);
}

@Override
protected void onStart() {
    super.onStart();
    lTop = gridLayout.getY();
    lLeft = gridLayout.getX();
    lBottom = lTop + gridLayout.getHeight();
    lRight = lLeft + gridLayout.getWidth();

}