ArrayAdapter requires ID to be a TextView error

﹥>﹥吖頭↗ 提交于 2019-11-28 02:05:50

You are probably using something like this (here the doc):

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.layout_1, values);

in that case your layout must be a simple layout with a TextView.

If you wanna use your own layout you need to write a custom adapter.

Build your own ArrayAdapter, then you can make the layout work however you would like.

The ArrayAdapter requires the resource ID to be a TextView XML exception means you don't supply what the ArrayAdapter expects. When you use this constructor:

new ArrayAdapter<String>(this, R.layout.a_layout_file, this.file)

R.Layout.a_layout_file must be the id of a xml layout file containing only a TextView(the TextView can't be wrapped by another layout, like a LinearLayout, RelativeLayout etc!), something like this:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" 
    // other attributes of the TextView
/>

If you want your list row layout to be something a little different then a simple TextView widget use this constructor:

new ArrayAdapter<String>(this, R.layout.a_layout_file, 
   R.id.the_id_of_a_textview_from_the_layout, this.file)

where you supply the id of a layout that can contain various views, but also must contain a TextView with and id(the third parameter) that you pass to your ArrayAdapter so it can know where to put the Strings in the row layout.

You seem to be on the right lines. I'm not sure the exact issue with your code as I've not compared closely, but it works in this example.

The full tutorial is here: Android tutorial for beginners - 97 - ListView with Custom Layout

This avoids the error ArrayAdapter requires ID to be a TextView which I was also getting.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!