android layout_weight 百分比,Android在垂直方向的LinearLayout中设置TextView百分比的最大宽度...

我想在下面的垂直方向的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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值