我在线性布局中添加了 10 个 TextView 。我得到所有 TextView 的所有坐标。我使用以下代码。
public class MainActivity extends Activity
{
TextView t[] = new TextView[10];;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout linear = (LinearLayout) findViewById(R.id.linear);
for(int i=0;i<10;i++)
{
t[i] = new TextView(this);
t[i].setTag(i);
String s = "Hello : "+i;
t[i].setText(s);
linear.addView(t[i]);
}
for(int i=0;i<10;i++)
{
float x0 = t[i].getX();
float y0 = t[i].getY();
float y1 = t[i].getWidth();
float x1 = x0 + t[i].getHeight();
Log.d(""+i, "x0 : "+x0 +" y0 : "+y0);
Log.d(""+i, "x0 : "+x0 +" y1 : "+y1);
Log.d(""+i, "x1 : "+x1 +" y0 : "+y0);
Log.d(""+i, "x1 : "+x1 +" y1 : "+y1);
}
}
所有 TextView 都显示在屏幕上。但是我一直都得到0。这段代码有什么问题?
最佳答案
问题是 LinearLayout 还没有经过它的 Measure 和 Layout passes。它包含那些对象,但它们现在“什么都不是”。
向 LinearLayout 发布一个 runnable 并做同样的事情:
linear.post(new Runnable()) {
// The view is now visible. Retrieve the objects and check.
}
关于android - 在运行时在android中获取textview数组的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20248416/