我想创建一个片段,它将静态菜单显示为列表中的一组行。
我喜欢在tableview中使用静态单元格的iOS方法。我怎样才能在android中实现这一点(因此不需要代码来定义元素,只需要xml)
是否有任何常规方法可以在xml中定义静态元素
(伪代码)
list_view.xml
<List view>
- use element my_row with onclick=row1_clicked and title="row 1"
- use element my_row with onclick=row2_clicked and title="row 2"
- use element my_row with onclick=row3_clicked and title="row 3"
- use element my_row with onclick=row4_clicked and title="row 4"
</List view>
my_row.xml
<My Row>
- text field (title should go here)
- on click (on click should go here)
</My Row>
所以基本上我想在列表中“包含”行并在xml级别上执行(无代码)。
答案 0 :(得分:21)
不幸的是,禁止通过xml列表视图定义。不过需要使用适配器混乱。
答案 1 :(得分:20)
使用字符串数组可以取得一些进展,例如
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/sports_array"/>
</LinearLayout>
与
结合<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="sports_array">
<item>Shuttle Badminton</item>
<item>Tennis</item>
<item>FootBall</item>
</string-array>
</resources>
答案 2 :(得分:12)
您可以使用嵌套在ScrollView中的垂直LinearLayout来获取您要查找的内容。将“listview”项放在LinearLayout中,并将它们设置为类似于listview的元素。
如果您绝对必须使用ListView(例如,您正在使用ListFragment),则必须使用ListAdapter子类或滚动自己的子类。
答案 3 :(得分:5)
其实还有办法! 使用包含 - 标记
重新使用布局只需定义要重复使用的布局。
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"/>
<ImageView
android:id="@+id/profileImage"
android:layout_width="128dp"
android:layout_height="128dp"
android:src="@drawable/lena" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/profileOnline"/>
</LinearLayout>
然后根据需要将其包含在ViewGroup中
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:gravity="center_horizontal">
<include layout="@layout/titlebar"/>
<TextView android:layout_width=”match_parent”
android:layout_height="wrap_content"
android:text="@string/hello"
android:padding="10dp" />
...
</LinearLayout>
您还可以通过在标记中指定它们来覆盖所包含布局的根视图的所有布局参数(任何android:layout_ *属性)。例如:
<include android:id=”@+id/news_title”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
layout=”@layout/title”/>
http://developer.android.com/training/improving-layouts/reusing-layouts.html
的更多信息