Android Activity和Fragment如何获取控件的高度和宽度
来源:互联网 发布:其无后乎的其什么意思 编辑:程序博客网 时间:2024/06/01 11:06
在 Activity的onCreate() 中调用某个按钮的 myButton.getHeight(),得到的结果永远是0
onCreate(): Height=0
onStart(): Height=0
onPostCreate(): Height=0
onResume(): Height=0
onPostResume(): Height=0
onAttachedToWindow(): Height=0
onWindowsFocusChanged(): Height=1845
可以看到,直到 onWinodwsFocusChanged() 函数被调用,我们才能得到正确的控件尺寸。其他 Hook 函数,包括在官方文档中,描述为在 Activity 完全启动后才调用的 onPostCreate() 和 onPostResume() 函数,均不能得到正确的结果。但是该方法只适用于Activity
对于Fragment可以采用下面的方法:
1. 使用 ViewTreeObserver 提供的 Hook 方法。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
myButton = (Button) findViewById(R.id.button1);
// 向 ViewTreeObserver 注册方法,以获取控件尺寸
ViewTreeObserver vto = myButton.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
int h = myButton.getHeight();
Log.i(TAG, "Height=" + h); // 得到正确结果
// 成功调用一次后,移除 Hook 方法,防止被反复调用
// removeGlobalOnLayoutListener() 方法在 API 16 后不再使用
// 使用新方法 removeOnGlobalLayoutListener() 代替
myButton.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
// ...
}
该方法在 onGlobalLayout() 方法将在控件完成绘制后调用,因而可以得到正确地结果。该方法在 Fragment 中,也可以使用。
2. 使用 View 的 post() 方法
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
myButton = (Button) findViewById(R.id.button1);
// 使用myButton 的 post() 方法
myButton.post(new Runnable() {
@Override
public void run() {
int h = myButton.getHeight();
Log.i(TAG, "Height=" + h); // 得到正确结果
}
});
// ...
}
- Android Activity和Fragment如何获取控件的高度和宽度
- android在OnCreate中获取控件的宽度和高度
- Android在OnCreate中获取控件的宽度和高度
- Android在OnCreate中获取控件的宽度和高度
- Android在OnCreate中获取控件的宽度和高度
- Android在OnCreate中获取控件的宽度和高度
- Android在OnCreate中获取控件的宽度和高度
- Android在OnCreate中获取控件的宽度和高度
- Android在OnCreate中获取控件的宽度和高度
- Android在OnCreate中获取控件的宽度和高度
- Android在OnCreate中获取控件的宽度和高度
- android在OnCreate中获取控件的宽度和高度.
- Android在OnCreate中获取控件的宽度和高度
- Android在OnCreate中获取控件的宽度和高度
- Android如何在onCreate()方法中获取控件的高度和宽度
- android如何获取屏幕宽度和高度
- android如何动态设置控件的高度和宽度
- Android 如何优雅的获取屏幕的高度和宽度
- AndroidStudio插件GsonFormat快速实现JavaBean
- Mysql字符集相关操作
- 文章标题
- 链接器都干了些什么?
- 10行Java代码实现最近被使用(LRU)缓存
- Android Activity和Fragment如何获取控件的高度和宽度
- 跳转页信息
- 杭电ACM2027java做法
- Android Studio无法检测到魅族手机的解决方法
- 社説 20150716 イラン核合意 中東安定への転換点になるか
- 内存测试Stream程序分析(一)--基本参数
- 存储过程知多少
- 把图片导出到excel中
- adf 自定义重复查询例子