您的位置:首页 > 其它

在Activity的onCreate方法中获取View的width和height

2015-03-19 18:09 375 查看
在Activity的onCreate方法中获取View的width和height都是0, 那么有没有方法可以获取到View的真实大小呢?

方法还是有滴, 就是实用view的post方法, post的方法的参数是一个Runnable, 其实run方法也是在主线程中执行的,

post方法内部做了一些操作, 其实是封装了一个Message添加到消息队列中去了, 源码中也多次使用了post方法,

有兴趣的同学可以查看源码好好研究一下,

闲话少说, 下面上代码:

public class DemoActivity2 extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.demo2);

final View v = findViewById(R.id.tv1);

Log.d("stone", "width=" + v.getWidth() + ", height=" + v.getHeight()); //width和height的值都是0

v.post(new Runnable() {

@Override

public void run() {

//此处可以获取到真实的width和height

Log.d("stone", "width=" + v.getWidth() + ", height=" + v.getHeight());

}

});

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: