【问题标题】:Android notifyDataSetChanged not workingAndroid notifyDataSetChanged 不起作用
【发布时间】:2015-02-27 09:16:53
【问题描述】:

我有一个适配器,它使用来自 TreeMap 的数据填充 ListView 和 2 个 TextView。 当用户从 ListView 添加或删除 Data 时,应刷新 View。

这是我的适配器:

public class MyAdapter extends BaseAdapter {
    private final ArrayList mData;

    public MyAdapter(Map<String, String> map) {
        mData = new ArrayList();
        mData.addAll(map.entrySet());
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public Map.Entry<String, String> getItem(int position) {
        return (Map.Entry) mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO implement you own logic with ID
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final View result;

        if (convertView == null) {
            result = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_adapter_item, parent, false);
        } else {
            result = convertView;
        }
    Map.Entry<String, String> item = getItem(position);

    // TODO replace findViewById by ViewHolder
    ((TextView) result.findViewById(android.R.id.text1)).setText(item.getKey());
    ((TextView) result.findViewById(android.R.id.text2)).setText(item.getValue());

    return result;
}}

因为我想从对话框更新视图,并且在我阅读的另一个问题上,需要从 UIThread 调用 notifyDataSetChanged(),所以我将 notifyDataSetChanged() 放入 Runnable。就是这样:

Runnable run = new Runnable(){
        public void run(){
            Log.v("in the Runnable: ", String.valueOf(colorHashMap));
            adapter.notifyDataSetChanged();
        }
    };

这就是在对话框中调用 Runnable 的方式:

DefaultColorActivity.this.runOnUiThread(run);

但无论我尝试或做什么,列表都不会更新。我需要关闭并重新打开活动以获取新列表。

【问题讨论】:

  • 您在哪里添加和删除列表视图代码中的数据?

标签: android listview android-arrayadapter notifydatasetchanged


【解决方案1】:

在您的adapter 中创建一个方法,例如:

 public void updateList(){
   notifyDataSetChanged() 
 }

当你想刷新列表时调用这个方法

【讨论】:

    【解决方案2】:

    从您的 Adapter 类(在 getView() 方法中)调用 notifyDataSetChanged() 方法,该方法在删除项目后扩展 BaseAdapter。

    【讨论】:

    【解决方案3】:

    首先,您必须在地图(适配器的数据源)中进行更改。并使用 Handler 类(Android OS Thread)像这样运行线程

        Handler handler=new Handler();
        handler.post(run);
    

    【讨论】:

      【解决方案4】:

      你不能创建列表对象。

      只需创建参考并将列表分配给您的列表

      在您的适配器类中删除此语句

      mData = new ArrayList();

      【讨论】:

        猜你喜欢
        • 2016-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-24
        • 2014-03-03
        相关资源
        最近更新 更多