public class Test extends Activity { PRivate LinearLayout mBackgroundLayout; private TextViewTest mTextViewTest; /** Called when the activity is first created. */ @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); // TODO Auto-generated constructor stub } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { // TODO Auto-generated method stub 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); // TODO Auto-generated constructor stub setText("test test "); } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); // measure(0, 0); Log.i("Tag", "width: " + getWidth() + ",height: " + getHeight()); Log.i("Tag", "MeasuredWidth: " + getMeasuredWidth() + ",MeasuredHeight: " + getMeasuredHeight()); } } } 這裡是在LinearLayout裡添加一個TextView控件,如果此時要得到對TextView獲取getWidth(),那麼是在TextView添加到Layout後再去獲取值,並不單單的是對TextView本身寬度的獲取。 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的內容佔據的實際寬度。 你如果想從一個最簡單的例子中的到它們的不同,下面將對上面的例子做一下修改: Java代码
public class Test extends Activity { private TextViewTest mTextViewTest; /** Called when the activity is first created. */ @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); // TODO Auto-generated constructor stub setText("test test "); } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); measure(0, 0); Log.i("Tag", "width: " + getWidth() + ",height: " + getHeight()); Log.i("Tag", "MeasuredWidth: " + getMeasuredWidth() + ",MeasuredHeight: " + getMeasuredHeight()); } } } 總結(正解): getWidth(): View在設定好佈局後整個View的寬度。 getMeasuredWidth(): 對View上的內容進行測量後得到的View內容佔據的寬度,前提是你必須在父佈局的onLayout()方法或者此View的onDraw()方法裡調用measure(0,0);(measure 參數的值你可以自己定義),否則你得到的結果和getWidth()得到的結果一樣。 也許我組織的不是很好,大家有什麼不清楚的地方再給我留言。關於這兩個方法的區別就是看你有沒有用measure()方法,當然measure()的位置也是很重要的。 转载自http://gundumw100.iteye.com/blog/1025191新闻热点
疑难解答