【问题标题】:Error: Cannot Resolve notifyDataSetChanged(); Android错误:无法解决 notifyDataSetChanged();安卓
【发布时间】:2015-01-24 18:21:42
【问题描述】:

我在更新我的 ListView 时遇到了一些问题。

所以我使用了 notifyDataSetChanged();但它说它无法解决。

这是代码中不起作用的部分:

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main_activity2);
    background2= (RelativeLayout) findViewById(R.id.background);
    final ListView theListView = (ListView) findViewById(R.id.listView);
    Intent calledActivity=getIntent();
    final List pe=calledActivity.getExtras().getStringArrayList("Caller1");

    String []s =new String[pe.size()];
    for(int i=0;i<pe.size();i++)
    {
        s[i]=(String)pe.get(i);
    }

            final ListAdapter theAdapter= new ArrayAdapter<String>(this,    android.R.layout.simple_list_item_1, pe);
             theListView.setAdapter(theAdapter);
    final int cnt=1;
    theListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String s1 = String.valueOf(parent.getItemAtPosition(position));
            pe.remove(s1);
            runOnUiThread(new Runnable() {
                public void run() {
                    theAdapter.notifyDataSetChanged();

                }
            });



        }
    });


    }

【问题讨论】:

  • 为什么theAdapter.notifyDataSetChanged(); 中有Runnable
  • 我把它看作是解决另一个人的问题
  • 您是否尝试过从Runnable 中删除theAdapter.notifyDataSetChanged(); 并将其直接放在pe.remove(s1); 之后?

标签: android listview notifydatasetchanged


【解决方案1】:

notifyDataSetChanged不是ListAdapter的方法,而是BaseAdapter的方法,(ArrayAdapter是BaseAdapter的子类)。要修复,您可以简单地转换 ListAdapter

theListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String s1 = String.valueOf(parent.getItemAtPosition(position));
            pe.remove(s1);
             ((BaseAdapter)theAdapter).notifyDataSetChanged();

【讨论】:

  • notifyDataSetChanged 也适用于ArrayAdapter。我用过,效果很好。
  • Gradle 需要一些时间,但我认为它应该可以工作。手指交叉。
  • 确实如此,但是如果您仔细查看操作的代码,您会注意到他正在将 ArrayApdater 实例分配给 ListAdapter @iRuth
  • @Blackbelt 是的,我使用了 ArrayAdapter,遵循 Derek Banas 的 YouTube 教程 no.3
  • 试试((ArrayAdapter)theAdapter).remove((String)parent.getItemAtPosition(position));
猜你喜欢
  • 2014-09-12
  • 2021-04-29
  • 2013-04-16
  • 2018-09-28
  • 2016-03-19
  • 2018-01-05
  • 1970-01-01
  • 2018-06-05
相关资源
最近更新 更多