View 或ViewGroup在创建时设置宽度高度为match_parent或者wrap_content时,通过getWidth()、getHeight()不能获取到真实的宽高。
错误及正确的方式分别如下:
int textviewWidth;
//mTextView width--match_parent height--wrap_content 不能正确获取宽高
LayoutParams params = (LayoutParams) mTextView.getLayoutParams();
if (params != null) {
textviewWidth = params.width;
}
//应使用下面的方式, 先按宽高对应模式进行测量,再获取
//mTextView.measure(View.MeasureSpec.AT_MOST, MeasureSpec.UNSPECIFIED); 不需要
textviewWidth = mTextView.getWidth();
小问题,记录下
本文探讨了在Android开发中,当View或ViewGroup的宽度和高度设置为match_parent或wrap_content时,如何正确获取其实际尺寸。指出直接使用getWidth()、getHeight()可能无法得到预期结果,而应通过LayoutParams或先进行测量再获取。
530

被折叠的 条评论
为什么被折叠?



