gpt4 book ai didi

java - 将 View 添加到 ListView 时出错

转载 作者:行者123 更新时间:2023-12-01 23:05:49 25 4
gpt4 key购买 nike

有一个空列表,我想向其中添加 TextView 。当我使用 addHeaderView 时它有效,但当我使用 addView 时它不起作用。这是代码:

    // 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);

这是我得到的错误:

addView(View) is not supported by AdapterView.

为什么会出现错误?有办法解决吗?

最佳答案

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

此外,如果您在 Activity 或适配器(其 getView 方法)的代码中使用 LayoutInflater.inflate 方法,请不要将 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

关于java - 将 View 添加到 ListView 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22766982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com