有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

向ListView添加视图时发生java错误

有一个空列表,我想在其中添加textView。它在我使用addHeaderView时有效,但在我使用addView时无效。代码如下:

    // Setup Adapter
    ArrayList<String> favList = new ArrayList<String>(Arrays.asList(mangas));
    favAdapt = new ArrayAdapter<String>(this,
            安卓.R.layout.simple_list_item_1, favList);
    favList.clear();

    TextView newText1 = new TextView(MyList.this);

    String hint = "No favorites selected yet";
    newText1.setText("No favorites selected yet");
    newText1.setTextColor(Color.rgb(140, 140, 140));
    newText1.setTextSize(20);
    newText1.setTypeface(Typeface.DEFAULT_BOLD);

    favListView.addHeaderView(newText1);
    favListView.addView(newText1);

    favListView.setAdapter(favAdapt);

以下是我得到的错误:

addView(View) is not supported by AdapterView.

为什么会有错误?有办法绕过它吗


共 (2) 个答案

  1. # 1 楼答案

    AdapterView的子类(如ListView)不能在布局文件或代码中手动添加子类。因此,如果你在一个布局中有这个:

    <ListView // .. other attributes>
         <// other views <  notice the children of the ListView tag
    </ListView>
    

    不要这样做,因为这将调用ListView的addView方法,引发异常。而是使用:

    <ListView // .. other attributes />
    < // other views
    

    您也不能在如下代码中使用ListView的任何addView方法:

    listViewReference.addView(anotherView); // <  don't do it
    

    另外,如果你使用Layoutiner。在活动或适配器(其getView方法)的代码中,不要将ListView作为第二个参数传递。例如,不要使用:

    convertView  = inflator.inflate(R.layout.child_rows, parent);
    

    正如Tamilarasi Sivaraj的回答一样,这将再次抛出异常。而是使用:

    convertView  = inflator.inflate(R.layout.child_rows, parent, false);
    

    答案在:Unable to start activity:UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView

  2. # 2 楼答案

    ListView子类^{},它覆盖ViewGroup.addView并抛出您正在接收的UnsupportedOperationException。这是没有办法的

    在子类化ArrayAdapter之后,可以在Adapter.getView中添加TextView。您也可以使用ListView.addHeaderViewListView.addFooterView。但是你不能像那样直接把View加到ListView