android权重的巧妙运用

来源:互联网 发布:白噪音真能效率 知乎 编辑:程序博客网 时间:2024/05/12 04:43

这里写图片描述


如图。今天一个项目需求是这样的,一个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)就是对线性布局指定方向(水平或垂直)上剩余空间分配的一个规则

1 1
原创粉丝点击