Android在适配器中更改数据

时间:2013-02-02 11:34:21

标签: android android-listview

我将此适配器用于ListView:

Appadapter extends ArrayAdapter<ResolveInfo> 
     private PackageManager pm=null;
     List<ResolveInfo> apps;
     AppAdapter(PackageManager pm, List<ResolveInfo> apps) {
    super(Launchalot.this, R.layout.row, apps);
  this.apps=apps;
  this.pm=pm;
}

@Override
public View getView(int position, View convertView,
                      ViewGroup parent) {
      Log.w(Launchalot.this.getPackageName(),"getView");
  if (convertView==null) {
    convertView=newView(parent);
  }

  bindView(position, convertView);

  return(convertView);
}

private View newView(ViewGroup parent) {
    Log.w(Launchalot.this.getPackageName(),"newView");
  return(getLayoutInflater().inflate(R.layout.row, parent, false));
}


private void bindView(int position, View row) {
  TextView label=(TextView)row.findViewById(R.id.label);
  Log.w(Launchalot.this.getPackageName(),"bindView");
  label.setText(getItem(position).loadLabel(pm));

  ImageView icon=(ImageView)row.findViewById(R.id.icon);

  icon.setImageDrawable(getItem(position).loadIcon(pm));
}
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
        setNotifyOnChange(true);}}

我在ListActivity类中使用此代码填充我的视图:

AppAdapter adapter=new AppAdapter(getPackageManager(), getResolveInfoList(0));
setListAdapter(adapter);

现在我更改了列表应用 我调用了notifyDataSetChanged()  但是,正如我所想,没有任何改变。请告诉我一个解决方案。 感谢

2 个答案:

答案 0 :(得分:8)

此信息仍不足以查看问题并为您提供帮助。这就是为什么我会用一个简单的例子来解释如何在notifyDataSetChanged();上使用MyCustomAdapter。 以下是如何填充适配器的示例:

private ArrayList<String> _names;
private MyCustomAdapter _adapter;
@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    _names = new ArrayList<String>();

    for(int i = 0; i < _names.size();i++){
        _names.add("Element : "+i);
    }

    _adapter = new MyCustomAdapter(this, _names);
    _myListView.setAdapter(_adapter);


}

private void refreshListView(){
    _names.clear();
    for(int i = 0; i < _names.size();i++){
        _names.add("New Element : "+i);
    }
    _adapter.notifyDataSetChanged();
}

这里的想法是更改您用于填充列表视图的List。清除它,用新数据填充它,然后调用notifyDataSetChanged();

就是这样。

答案 1 :(得分:1)

短而快,在您感觉数据集中已完成更改后调用这两行。

AppAdapter adapter=new AppAdapter(getPackageManager(), getResolveInfoList(0));
setListAdapter(adapter);