如何解决ArrayAdapter requires the resource ID to be a TextView

2025-03-23 21:02:07
推荐回答(1个)
回答1:

  今天碰到这样一个难题,搞了很久都没搞定,到网上搜索了一下,发现有很多人都在问这样的问题,现在将自己解决和分析的结果放置如下:
  在arrayadapter()这个类中有多个构造方法,我仅据此列以作代表
  public ArrayAdapter(Context context ,int textViewResourceId ,List objects)
Constructor
  参数:
  context ----》 The current context
textViewResourceId ---->the resource ID for a layout file contain a TextView to use when instantiating views.
List objects ---> the objects to represent in the ListView

  第一个参数自不必说,上下文
  第二个参数的意思是说 当装载在这个构造函数中的layout 时,其layout的ID 必须是一个TextView,简言之,第2个参数应该是ListView中每个选择项的样式,可以使用系统自带的android.R.layout.xxx,也可以是自定义的,仅包含TextView。
  第三个参数也不必说了
  那么解决这个问题的时候,你的main.xml要更改为:
  
android:layout_height="wrap_content" />

  因为根节点必须是TextView,不然就会抛“ArrayAdapter requires the resource ID to be a TextView”