我在互联网上搜索了大约一段时间,试图找到一些有关 XML 设计的指南。
到目前为止,我发现最好的设计是保持布局“平坦”,这意味着将布局嵌套保持在最低限度。
基本上我将下面的四个布局堆叠在一起。我没有计划添加超过 4 个。每个之间唯一不同的是 simple_detail_image 中的图像。我发现的选项正在使用 <include>
对于每个项目,然后以编程方式更改图像。
这是最佳实践还是有更实用的方法?
我探索过的另一个选择是制作 ListView
并用这些填充它,但这似乎有点矫枉过正。
<?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="wrap_content"
android:background="@drawable/shape_rounded"
android:padding="4dp"
android:orientation="horizontal">
<ImageView
android:id="@+id/simple_detail_image"
android:layout_width="72dp"
android:layout_height="72dp"
android:src="@drawable/ic_launcher"/>
<TextView
android:id="@+id/simple_detail_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="12dp"
android:layout_marginStart="12dp"
android:text="Hi"/>
<Space
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"/>
<ImageView
android:layout_gravity="center"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_marginRight="@dimen/chevron_horizontal_margin"
android:layout_marginEnd="@dimen/chevron_horizontal_margin"
android:src="@drawable/ic_chevron_gray"/>
</LinearLayout>
最佳答案
您可以使用单个 TextView 代替整个布局来简化整个事情,没有图像也没有容器。
因为一个 TextView 可以同时包含不同的复合 drawable。
例如:
android:drawablePadding="4dp"
android:drawableLeft="@drawable/ic_launcher"
android:drawableRight="@drawable/ic_chevron_gray"
您可以在外部(垂直)容器中包含 4 个 TextView,这样就完成了。
然后,在代码中,更改 drawableLeft:
//public void setCompoundDrawablesWithIntrinsicBounds (int left, int top, int right, int bottom)
public void setCompoundDrawablesWithIntrinsicBounds (R.drawable.your_left_drawable_1, 0, R.drawable.ic_chevron_gray, 0);
这将使您的布局非常扁平且高效。
关于Android适当的布局设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26210416/