Android getLayoutParams.width vs getWidth()
我有以下看法:Android getLayoutParams.width vs getWidth(),android,Android,我有以下看法: <View android:id="@+id/divider" android:layout_height="2dp" android:background="#ffffff" android:layout_below="@+id/timer" android:layout_width="wrap_content" /> 问题是,divider.getLayoutParams().wid
<View
android:id="@+id/divider"
android:layout_height="2dp"
android:background="#ffffff"
android:layout_below="@+id/timer"
android:layout_width="wrap_content" />
问题是,divider.getLayoutParams().width
的值为-1,而divider.getWidth()
的值是正确的(即剩余的秒数)
随着时间的流逝,我需要动态地改变视图的宽度
divider.setLayoutParams().width
是一个很好的选择。但是,它没有改变布局宽度,布局宽度仍然保持-1,请尝试使用以下代码
int widthSpec = View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.UNSPECIFIED,
View.MeasureSpec.UNSPECIFIED);
viewObject.measure(widthSpec, widthSpec);
int height = viewObject.getMeasuredHeight();
int width = viewObject.getMeasuredWidth();
getLayoutParams().width
在宽度为MATCH\u PARENT
时返回-1getLayoutParams()。宽度可以是FILL\u PARENT
(在API级别8中替换为MATCH\u PARENT
)或WRAP\u CONTENT
或精确大小。但是getWidth()
总是以像素为单位返回宽度。奇怪的是,在记录变量width
时,我看到它返回0。我正在寻找一个动态的宽度设置器。您可以通过布局参数动态设置宽度和高度。你试过了吗?是的,我试过了。它本应该起作用,但不会改变任何事情getLayoutParams().width
仍返回-1。但为此,您需要在动态更改视图时测量视图。尝试在我的代码中指定View.MeasureSpec.UNSPECIFIED而不是“0”。
int widthSpec = View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.UNSPECIFIED,
View.MeasureSpec.UNSPECIFIED);
viewObject.measure(widthSpec, widthSpec);
int height = viewObject.getMeasuredHeight();
int width = viewObject.getMeasuredWidth();