Android中Activity获取View宽高的常用方式

Android开发中,onCreate()onStart()onResume()关键生命周期方法中获取某控件的宽高,然而获取的结果均为 0,Why?

Because:View的measure()与Activity的生命周期没有同步执行,因此不能保证在onCreate()onStart()onResume()中获取控件宽高时,这个View已经测量结束,so,如果没有测量完成,我们取得的宽高就是0。

Activity中测试代码,具体看注释即可:

public class MainActivity extends AppCompatActivity {
   
    private static final String TAG = "MainActivity";
    private Button button;// Activity获取View的宽高
    private boolean isFirstFocus = true;
    private int hightBtn, widthBtn;

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

        // View的measure()过程和Activity的生命周期方法不是同步执行的
        // 无法保证Activity执行了onCreate()、onStart()、onResume()时某个View已经测量完毕
        hightBtn = button.getHeight();
        widthBtn = button.getWidth();
        //code1 button's Height:0,Width:0
        Log.d(TAG, "code1 button's Height:" + hightBtn + ",Width:" + widthBtn);

		// 手动调用View的measure()方法后获取——具体值模式可用,此处match_parent无效
        int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.EXACTLY);
        int height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.EXACTLY);
        button.measure(width, height);
        hightBtn = button.getMeasuredHeight();
        widthBtn = button.getMeasuredWidth();
        // code2 button's Height:0,Width:0
        Log.d(TAG, "code2 button's Height:" + hightBtn + ",Width:" + widthBtn);

		// 手动调用View的measure()方法后获取——wrap_content可用
        width =
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小山研磨代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值