我想在下面的垂直方向的LinearLayout中将带有tv_long_text的TextView的layout_weight设置为80%.
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical">
android:id="@+id/tv_short_text"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
tools:text="short text" />
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" />
上述方法无法正常工作,因为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个额外视图.有没有其他有效的方法来做到这一点?
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical">
android:id="@+id/tv_short_text"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
tools:text="short text" />
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
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" />
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.2"/>
解决方法:
我不会试图摆弄运行时测量.具有第二个水平布局的解决方案非常精细,因为您有两个水平扩展的TextView.
另一个选项是来自支持库com.android.support:percent:25.1.0 See here的PercentRelativeLayout
这是来自文档
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
app:layout_widthPercent="50%"
app:layout_heightPercent="50%"
app:layout_marginTopPercent="25%"
app:layout_marginLeftPercent="25%"/>
标签:android,android-linearlayout,android-layout-weight
来源: https://codeday.me/bug/20190611/1218143.html