首先要明白一点就是一般情况下,我们在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);
}
});