android权重的巧妙运用

本文详细介绍了如何在ListViewItem中实现文字居中显示、图标始终位于右侧,并解决文字长度过长导致的问题。通过使用LinearLayout和设置布局权重,实现了文字和图片的合理布局和长度限制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里写图片描述


如图。今天一个项目需求是这样的,一个listview的item是简单的文字加图标,应该来说是挺简单的,但是他有一个需求:
1、图标永远是居右边显示。
2、文字最长显示到图标的左边,多余的用省略号显示。
问题分析:先按思路来,写出一个简单的item,如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:singleLine="true"
        android:layout_marginRight="10dp"
        android:text="11" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:src="@mipmap/icon_login_user" />
</RelativeLayout>

问题来了,当我字数过长的时候,发现会直接覆盖到图标上面。那简单,我们设置一下。

android:maxLength="11"

试了一步手机发现没有问题,但是不同分辨率的手机发现,分辨率越高,我一行可以显示更多的字,但是这边直接被写死了,看上去就显得不协调。如下图:
分辨率768*1280
分辨率768*1280
分辨率280*280
分辨率280*280

长度又不能写死,但是又得限制他的长度该如何呢,这时候权重就有大用处了。
先看代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="10dp"
        android:ellipsize="end"
        android:singleLine="true"
        android:layout_weight="1"/>

    <ImageView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:src="@mipmap/icon_login_user"
        android:layout_weight="0"/>
</LinearLayout>

这里把imagview的权重设置为0,textview的权重设置为1,Android在显示的时候会优先满足ImageView,然后把剩下的宽度分配给TextView.

接下来看看官方给的权重解释:
权重(layout_weight)就是对线性布局指定方向(水平或垂直)上剩余空间分配的一个规则

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值