Android布局技巧之创建高效布局

2019-12-10 17:56:46王振洲

如果你将它作为ListView的item,它能正常工作,但却是相当浪费的。相同的布局可以使用RelativeLayout进行重写,相对于每个列表项来说,可以节省一个View,且View层级上更好,只有一层。使用RelativeLayout也很简单:

<RelativeLayout xmlns:android="http://www.easck.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="?android:attr/listPreferredItemHeight"
  android:padding="6dip">
  <ImageView
    android:id="@+id/icon"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_alignParentTop="true"
    android:layout_alignParentBottom="true"
    android:layout_marginRight="6dip"
    android:src="@drawable/icon" />
<TextView 
    android:id="@+id/secondLine"
    android:layout_width="fill_parent"
    android:layout_height="26dip" 
    android:layout_toRightOf="@id/icon"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:singleLine="true"
    android:ellipsize="marquee"
    android:text="Simple application that shows how to use RelativeLayout" />
  <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@id/icon"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_above="@id/secondLine"
    android:layout_alignWithParentIfMissing="true"
    android:gravity="center_vertical"
    android:text="My Application" />
</RelativeLayout>

新的实现与老的实现看起来效果完全一致,除了一种情况。每个列表项显示两行文字:标题和可选的描述。当某一个列表项的描述不可获得时,应用程序可能希望将第二个TextView的Visibility设为GONE。LinearLayout实现版表现得很完美,但RelativeLayout实现版就有点差强人意了:

Android布局