在android的自定义View的构造方法,或者在Activity的onCreate方法调用view的getWidth和getHeight方法返回的值是0,可以通过以下三种方法获得width和height
一、自定义View的onMeasure
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Log.i(TAG,String.format("onMeasure width = %d,height=%d",getWidth(),getHeight()));
}
二、View的getViewTreeObserver().addOnGlobalLayoutListener
this.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
{
@Override
public void onGlobalLayout()
{
Log.i(TAG,String.format("getViewTreeObserver width = %d,height=%d",getWidth(),getHeight()));
}
});
三、View的post方法
this.post(new Runnable()
{
@Override
public void run()
{
Log.i(TAG,String.format("post width = %d,height=%d",getWidth(),getHeight()));
}
});
完整代码
package com.junjiex.status.view;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
/**
* @author 172042886@qq.com
* @time 2016/3/23.16:18
*/
public class TestView extends LinearLayout
{
private static final String TAG ="TestView";
public TestView(Context context, AttributeSet attrs)
{
super(context, attrs);
init(context);
}
private void init(Context context)
{
int width = getWidth();
int height = getHeight();
Log.i(TAG,String.format("init width = %d,height=%d",width,height));
this.post(new Runnable()
{
@Override
public void run()
{
Log.i(TAG,String.format("post width = %d,height=%d",getWidth(),getHeight()));
}
});
this.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
{
@Override
public void onGlobalLayout()
{
Log.i(TAG,String.format("getViewTreeObserver width = %d,height=%d",getWidth(),getHeight()));
}
});
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Log.i(TAG,String.format("onMeasure width = %d,height=%d",getWidth(),getHeight()));
}
}
代码运行结果
03-23 16:40:17.888 17371-17371/com.junjiex.status I/TestView: init width = 0,height=0
03-23 16:40:17.908 17371-17371/com.junjiex.status I/TestView: onMeasure width = 0,height=0
03-23 16:40:17.908 17371-17371/com.junjiex.status I/TestView: onMeasure width = 0,height=0
03-23 16:40:17.938 17371-17371/com.junjiex.status I/TestView: getViewTreeObserver width = 984,height=1824
03-23 16:40:17.938 17371-17371/com.junjiex.status I/TestView: post width = 984,height=1824
03-23 16:40:17.948 17371-17371/com.junjiex.status I/TestView: onMeasure width = 984,height=1824
03-23 16:40:17.948 17371-17371/com.junjiex.status I/TestView: onMeasure width = 984,height=1824
03-23 16:40:17.948 17371-17371/com.junjiex.status I/TestView: getViewTreeObserver width = 984,height=1824