textView的位置返回0,0

时间:2014-05-19 19:22:04

标签: android

我有两个textView个对象,其中一个是"@+id/touchView",另一个是"@+id/viewLocat"。我希望viewLocat在活动开始时显示touchView的坐标。

这是我到目前为止所做的(在我的.java文件中):

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        View touchView = findViewById(R.id.touchView);
        TextView viewLocat = (TextView)findViewById(R.id.viewLocat);
        int[] viewLocation = new int[2];
        touchView.getLocationOnScreen(viewLocation);
        viewLocat.setText(String.valueOf(viewLocation[0]) + "x" + String.valueOf(viewLocation[1]));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

但是,当我开始活动时,textView中的值为0,0

我还尝试了另一种方法,如下所示(也在.java文件中):

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        View touchView = findViewById(R.id.touchView);
        TextView viewLocat = (TextView)findViewById(R.id.viewLocat);
        viewLocat.setText(String.valueOf(touchView.getTop()));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

但是,这只会返回0如何让代码返回TextView相对于其父LinearLayout的坐标

1 个答案:

答案 0 :(得分:0)

在布局之前,您的观点不会返回正确的信息。