【转】Android getWidth和getMeasuredWidth
程序员文章站
2022-07-14 17:40:27
...
以前做项目的时候用到过,也不是很明白,现在看了别人的总结,转来。。。
代码一
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 的空間。
推荐阅读
-
Android系统的智能指针(轻量级指针、强指针和弱指针)的实现原理分析【转】
-
(转)自定义Android的ListView布局和各Item的背景色
-
(转)android开发中实现个性化ListView的一些概念和思路
-
(转)自定义Android的ListView布局和各Item的背景色
-
(转)android开发中实现个性化ListView的一些概念和思路
-
android之view获取getWidth()和getHeight()
-
android view getWidth 和 getHeight 的值为0
-
Android之View的知识(getWidth() 和getMeasuredWidth区别 如何在oncreate获取宽高)
-
【转】Android getWidth和getMeasuredWidth
-
.NET(WinCE、WM)转Android开发——Xamarin和Smobiler对比