【发布时间】:2017-07-17 16:32:43
【问题描述】:
我想将TextView 的layout_weight 与tv_long_text 设置为以下LinearLayout 的vertical 的80% > 方向。
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tv_short_text"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
tools:text="short text" />
<TextView
android:id="@+id/tv_long_text"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="0.8"
tools:text="a pretty long text" />
</LinearLayout>
上述方法不起作用,因为 textview 父级的方向是垂直的。
所以,我尝试在 xml 中设置 android:layout_width="match_parent",然后 通过获取测量的宽度在运行时设置宽度,然后将宽度设置为 80%,但 getMeasuredWidth 是给我0。
int measuredWidth = longTextView.getMeasuredWidth();
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) longTextView.getLayoutParams();
params.width = (int) (measuredWidth * 0.8);
longTextView.setLayoutParams(params);
我也尝试在运行时设置 layout_weight,但它也不起作用,可能是因为它的父视图是垂直方向的。
longTextView.setLayoutParams(
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.MATCH_PARENT,
0.8f)
);
对我有用的是为长文本视图添加一些额外视图。但是为了尝试以百分比设置此视图的宽度,又添加了 2 个额外的视图。 还有其他有效的方法吗?
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tv_short_text"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
tools:text="short text" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_long_text"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="0.8"
android:textStyle="bold"
tools:text="a pretty long text" />
<View
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.2"/>
</LinearLayout>
</LinearLayout>
【问题讨论】:
标签: android android-linearlayout android-layout-weight