1. 直接获取宽高
布局:
<TextView
android:id="@+id/textview"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="#f00"
android:text="Hello World!"/>
Java:
mTextView = (TextView) findViewById(R.id.textview);
mWidth = mTextView.getWidth();
mHeight = mTextView.getHeight();
Log.d(TAG, " width = " + mWidth + " height = " + mHeight);
Log:
width = 0 height = 0
由此可见,在onCreate中直接获取宽高得到的都是0
2. 通过 View.post(Runnable action)
代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.textview);
mTextView.post(new Runnable() {
@Override
public void run() {
mWidth = mTextView.getWidth();
mHeight = mTextView.getHeight();
Log.d(TAG, "width = " + mWidth + " height = " + mHeight);
}
});
Log:
width = 600 height = 600
所以,在onCreate中可以使用View.post方法替代直接getWidth()和getHeight()来获取宽高