以前做项目的时候用到过,也不是很明白,现在看了别人的总结,转来。。。
代码一
public class MainActivity extends Activity {
private LinearLayout mBackgroundLayout;
private TextViewTest mTextViewTest;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBackgroundLayout = new MyLayout(this);
mBackgroundLayout.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT));
mTextViewTest = new TextViewTest(this);
mBackgroundLayout.addView(mTextViewTest);
setContentView(mBackgroundLayout);
}
public class MyLayout extends LinearLayout {
public MyLayout(Context context) {
super(context);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
Log.i("Tag", "--------------");
View mView = getChildAt(0);
mView.measure(0, 0);
}
}
public class TextViewTest extends TextView {
public TextViewTest(Context context) {
super(context);
setText("test test ");
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
measure(0, 0);
Log.i("Tag", "width: " + getWidth() + ",height: " + getHeight());
Log.i("Tag", "MeasuredWidth: " + getMeasuredWidth()
+ ",MeasuredHeight: " + getMeasuredHeight());
}
}
}
出来的LOG
width: 78,height: 29
MeasuredWidth: 78,MeasuredHeight: 29
代码2
public class MainActivity extends Activity {
private TextViewTest mTextViewTest;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTextViewTest = new TextViewTest(this);
setContentView(mTextViewTest);
}
public class TextViewTest extends TextView {
public TextViewTest(Context context) {
super(context);
setText("test test ");
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
measure(0, 0);
Log.i("Tag", "width: " + getWidth() + ",height: " + getHeight());
Log.i("Tag", "MeasuredWidth: " + getMeasuredWidth()
+ ",MeasuredHeight: " + getMeasuredHeight());
}
}
}
出来的log
width: 480,height: 724
MeasuredWidth: 78,MeasuredHeight: 29
getMeasuredWidth():API里面
The width of this view as measured in the most recent call to measure(). This should be used during measurement and layout calculations only.
得到的是在最近一次调用measure()方法测量后得到的view的宽度,它仅仅用在测量和layout的计算中。
所以此方法得到的是view的内容占据的实际宽度
总结:
getwidth(): view在设定好布局后整个view的宽度。
getMeasuredWidth(): 对view上的内容进行测量后得到的view内容占据的宽度,前提是你必须在父布局的onLayout()方法或者此view的onDraw()方法里调用measure(0,0);(measure 参数的值你可以自己定义),否则你得到的结果和getWidth()一样。
.請尊重原創,轉載請註明這是 http://hi.baidu.com/ljlkings/home 的空間。