如何在不扩展List活动的情况下创建自定义Listview?

时间:2015-03-25 09:19:14

标签: xamarin xamarin.android

我想创建一个包含A图像和文本的自定义布局的列表视图

但我找到的所有教程都扩展了List Activity但我无法扩展List Activity,因为我需要在布局中添加按钮和其他东西。 我需要使用自定义项目布局

来使用ListView

关于如何做的任何想法?

1 个答案:

答案 0 :(得分:1)

您无需使用ListActivity即可在布局中使用ListView。所有使用ListActivity的样本都在那里,因为人们很懒;)

因此,只需使用常规Activity,然后您只需将ListView添加到您要设置为内容视图的布局中。这看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="0"
        android:layout_weight="1" />
    <Button
        android:id="@+id/somethingButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Do something" />
    <Button
        android:id="@+id/elseButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Do something else" />
</LinearLayout>

然后与Activity方法中的任何其他OnCreate一样:

SetContentView(Resource.Layout.myLayout); // myLayout.axml

var listView = FindViewById<ListView>(Resource.Id.listView);
listView.Adapter = new MyAdapter(context, itemsSource);

var somethingButton = FindViewById<Button>(Resource.Id.somethingButton);
var elseButton = FindViewById<Button>(Resource.Id.elseButton);

... more code ...

ListView就像其他任何布局一样,所以没有任何神奇之处。此示例中的MyAdapter是您实现的内容,它会获取您的数据并以所需的图像和文本布局显示。

有关ListViewAdapter的更多信息,请refer to the excellent documentation which Xamarin provides