【问题标题】:Android: ArrayAdapter requires the resource ID to be a TextView?Android:ArrayAdapter 要求资源 ID 为 TextView?
【发布时间】:2016-03-09 17:55:08
【问题描述】:

我正在尝试实现一个代码,其中使用数组适配器将线性布局列表插入到列表视图中。每个线性布局包含两个子视图。这是xml。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/list_item"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/list_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"/>

    <TextView
        android:id="@+id/list_label"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginLeft="10dp"
        android:padding="10dp"
        android:textSize="16sp" />

</LinearLayout>

现在我在片段中创建了一个这样的代码 sn-p。

    final String[] my_page_items = getResources().getStringArray(R.array.my_page_items);

    int[] my_page_icons = {
            R.mipmap.ic_about,
            R.mipmap.ic_app_settings,
            R.mipmap.ic_account_settings,
            R.mipmap.ic_logout
    };

    LinearLayout[] items = new LinearLayout[my_page_items.length];
    TextView[] labels = new TextView[my_page_items.length];
    ImageView[] icons = new ImageView[my_page_icons.length];

    for(int i=0; i<my_page_icons.length; i++) {
        items[i] = (LinearLayout) LayoutInflater.from(getActivity().getApplication()).inflate(R.layout.list_item, null);
        labels[i] = (TextView) items[i].findViewById(R.id.list_label);
        icons[i] = (ImageView) items[i].findViewById(R.id.list_icon);

        labels[i].setText(my_page_items[i]);
        icons[i].setBackground(getResources().getDrawable(my_page_icons[i]));
    }


    setListAdapter(new ArrayAdapter<>(getActivity(), R.layout.list_item, items));
    lv = getListView();

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    });

当我运行这段代码时,我在 logcat 中得到以下内容。

java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView

这个问题应该如何解决?

【问题讨论】:

    标签: android android-layout android-listview android-arrayadapter illegalstateexception


    【解决方案1】:

    new ArrayAdapter<>(getActivity(), R.layout.list_item, items)
    

    R.Layout.list_item 必须是仅包含TextView 的 xml 布局文件的 id(TextView 不能被其他布局包裹,如 LinearLayout、RelativeLayout 等!),

    编辑可能的解决方案:

    如果你想让你的列表行布局有点不同,那么一个简单的 TextView 小部件使用这个构造函数:

    new ArrayAdapter<>(getActivity(), R.layout.list_item, R.id.id_of_your_textview items)
    

    您在其中提供可以包含各种视图的布局的 id,但还必须包含 TextView 和您传递给 ArrayAdapter 的 id(第三个参数),以便它可以知道将字符串放在行布局中的位置.

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-12
    • 2012-03-06
    • 1970-01-01
    • 2015-10-15
    相关资源
    最近更新 更多