0

There is an empty list to which I want to add a textView. It works when I use addHeaderView but not when I use addView. Here is the code:

    // Setup Adapter
    ArrayList<String> favList = new ArrayList<String>(Arrays.asList(mangas));
    favAdapt = new ArrayAdapter<String>(this,
            android.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);

Here is the error I get:

addView(View) is not supported by AdapterView.

Why is there an error? Is there a way around it?

solalito
  • 1,189
  • 4
  • 19
  • 34
  • why would you do that? you already have an adapter, you can add headers or footers, but if you need to add view in the listview, it means you need to add data in the adapter. – njzk2 Mar 31 '14 at 16:36
  • mainly just wanted to know why it happened – solalito Mar 31 '14 at 16:39

2 Answers2

2

A subclass of AdapterView like a ListView can't have children manually added either in the layout file or added in code. So if you have this in one of your layouts:

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

don't do it, as this will call the addView method of ListView, throwing the exception. Instead use:

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

You also can't use any of the addView methods of ListView in code like this:

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

Also, if you use the LayoutInflater.inflate method in the code of the Activity or the adapter(its getView method), don't pass the ListView as the second parameter. For example, don't use:

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

as in Tamilarasi Sivaraj's answer as that will throw the exception again. Instead use:

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

Answer found at: Unable to start activity:UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView

Community
  • 1
  • 1
Matej Špilár
  • 2,617
  • 3
  • 15
  • 28
1

ListView subclasses AdapterView, which overrides ViewGroup.addView and throws the UnsupportedOperationException you're receiving. There is no way around that.

You could add your TextView in Adapter.getView after subclassing ArrayAdapter. You could also use ListView.addHeaderView or ListView.addFooterView. But you can't directly add the View to your ListView like that.

adneal
  • 30,484
  • 10
  • 122
  • 151