在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());
}
});
}
}
方法还是有滴, 就是实用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());
}
});
}
}
相关文章推荐
- 解决在onCreate()过程中获取View的width和Height为0的4种方法
- 解决在onCreate()过程中获取View的width和Height为0的4种方法
- 解决在onCreate()过程中获取View的width和Height为0的4种方法
- 在onCreate()方法中获取view的width和height
- 解决在onCreate()过程中获取View的width和Height为0的方法
- Android解决在onCreate()中获取View的width、Height为0的方法
- 在Activity中的OnCreate中,获取控件TextView的width及height
- 解决在onCreate()过程中获取View的width和Height为0的几种方法
- 解决在onCreate()过程中获取View的width和Height为0的4种方法
- 解决在onCreate()过程中获取View的width和Height为0的4种方法
- 实现杂记(27):解决在onCreate()过程中获取View的width和Height为0的4种方法
- android在oncreate()方法中获取view的宽高width,height
- 解决在onCreate()过程中获取View的width和Height为0的4种方法
- 解决在onCreate()过程中获取View的width和Height为0的4种方法
- 解决在onCreate()过程中获取View的width和Height为0的4种方法
- 解决在onCreate()过程中获取View的width和Height为0的4种方法
- 解决在onCreate()过程中获取View的width和Height为0的方法
- 解决在onCreate()过程中获取View的width和Height为0的方法
- 解决在onCreate()过程中获取View的width和Height为0的4种方法
- 解决在onCreate()过程中获取View的width和Height为0的4种方法