当View为GONE状态时获取View的宽高

首先要明白一点就是一般情况下,我们在Activity里面的onCreate里面获取View宽高,可以采用:

(1)View布局完成的监听

button.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
  @Override
  public void onGlobalLayout(){
    //here you can get size
    width = button.getWidth();
    height = button.getHeight();
    button.getViewTreeObserver().removeGlobalOnLayoutListener(this);
  }
});

(2)post里面进行获取

button.post(new Runnable() {
    @Override
    public void run() {
	//here you can get size
        width = button.getWidth();
        height = button.getHeight();
    }
});

但是要注意就是很多时候,我们的View的状态时GONE的。

在此状态下使用上面两种方式都是不能获取对应的宽高的,而INVISIBLE状态时可以的。

INVISIBLE状态,系统会给View保留位置,也就是说View的宽高是已经算好了的,只是不进行渲染。

而GONE状态,系统不仅仅不会计算宽高,当然也不会渲染了。


问题如何获取View为GONE状态下的宽高呢?

有个小技巧就是,在xml中先将View设置设置为INVISIBLE,然后在onCreate中,在post中获取宽高,然后将View设置为GONE就可以了。

<TextView
            android:id="@+id/txt"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp"
            android:background="#ff00ff"
            android:gravity="center"
            android:text="读书"
            android:textColor="#ffffff"
            android:textSize="32sp"
            android:visibility="invisible" />

txt = (TextView) findViewById(R.id.txt);

        txt.post(new Runnable() {
                @Override
                public void run() {
                    width = txt.getWidth();
                    height = txt.getHeight();
                    txt.setVisibility(View.GONE);
                }
        });




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值