ListView中的Android自定义列表项

标签 android listview listitem

我试图制作一个简单的自定义 ListView 列表项来帮助我理解它是如何工作的,但它不起作用。

当我在 MainActivity.java 中使用注释行时,一切正常(它使用内置布局)。 但是当我尝试自己的布局 row_layout 而不是 simple_list_item_1 时,我在启动程序时遇到了 ANR。

主 Activity .java

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    String[] colors = {"blue", "red", "yellow", "green", "purple", "orange"};

    //ListAdapter listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, colors);
    ListAdapter listAdapter = new ArrayAdapter<String>(this, R.layout.row_layout, colors);

    ListView listView = (ListView)findViewById(R.id.theListView);

    listView.setAdapter(listAdapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String auswahl = "Auswahl:" + String.valueOf(parent.getItemAtPosition(position));

            Toast.makeText(MainActivity.this, auswahl, Toast.LENGTH_LONG).show();
        }
    });
}

activity_main.xml

<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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/theListView"></ListView></LinearLayout>

行布局.xml

<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"
tools:context=".MainActivity">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/textView1"
    android:textSize="30sp"
    android:textStyle="bold"
    android:padding="15dp"/></LinearLayout>

最佳答案

调用适配器时,您需要在自定义行中提供 TextView 的 ID。

ListAdapter listAdapter = new ArrayAdapter<String>(this, R.layout.row_layout, R.id.textView1, colors);

关于ListView中的Android自定义列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30752287/

相关文章:

c# - 减少闪烁时使用 C# Listview 模糊文本

android - onItemClick listView 关闭一个,最后单击的项目导致崩溃?

Android:onListItemClick 未打开 .xml 文件

android - 是否可以使用 XML 文件中的动画将图像居中?

android - 如何计算合适的android小部件大小?

Android 媒体查看器 SDK(相当于 iOS QLPreviewController)

listview - 更改其对齐方式后如何重新绘制列表控件?

sharepoint - 使用事件接收器更新项目的 'Title' 字段

asp.net - 将 ListItems 从通用列表添加到 DropDownList

java - 从apk文件中提取包名