我有一个名为 myListView
的 ListView
,我想用 3 个名为 layout1.xml 的
、LinearLayout
元素填充它layout2.xml
和 layout3.xml
。所有 3 个 LinearLayout
元素都非常相似;这是其中之一:
<?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"
android:orientation="horizontal" >
<TextView
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Los Angeles" />
<TextView
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="California" />
</LinearLayout>
我的目标是用这三个 LinearLayout
元素填充 ListView
(myListView
)。有谁知道我该怎么做?
最佳答案
首先,如果所有三种线性布局都相似,我建议您只使用一种。
无论如何,您必须为 ListView 使用自定义适配器。例如,您创建一个扩展 ArrayAdapter 的类。如果你对自定义适配器不熟悉,我建议你看一下here 。
在 getView 方法中,您实际上必须根据单元格位置来膨胀不同的 *.xml。因此:
@Override
puclic View getView (int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
switch (position) {
case 0: view = inflater.inflate(R.layout.my_layout_1, null, true);
//rest of my code
break;
case 1: view = inflater.inflate(R.layout.my_layout_2, null, true);
//rest of my code
break;
case 2: view = inflater.inflate(R.layout.my_layout_3, null, true);
//rest of my code
break;
default: break;
//rest of my code
return view;
}
关于java - Android:将 LinearLayout 设置为 Listview 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25171533/