Android notifyDataSetChanged()示例

时间:2014-07-03 16:11:57

标签: android android-listview notifydatasetchanged

有人可以给我一个示例教程或指导我在我的适配器中使用notifyDataSetChanged()吗?我从数据库中获取数据并填写listview。同样在我的listview中,我有一个按钮,可以更新我的数据库值将更新的特定内容,按钮文本将更改为“喜欢”。但我不知道如何使用数据库中的数据再次刷新我的列表视图。

1 个答案:

答案 0 :(得分:1)

修改

在适配器

中为数组列表创建自定义类
public class Entity   {
int id;
variables ..........
boolean isLiked = false;

public Entity(some values){
  // set the id;
  variables = values ;
}
public void setLiked(boolean like){
   this.isLiked = like; 
   // you must update database here
 }
public boolean IsLiked(){ return this.isLiked; } 

}

创建自定义适配器

public class EntityAdapter extends ArrayAdapter<Entity> { 
.................................
........other methods............
.................................

public View getView(int position, View convertView, ViewGroup parent) {

    final Entity entity = arrayList.get(position);

    final ViewHolder holder;
    View view = convertView;
     if (view == null) {

        int layoutCode=this.layoutcode;


        view = ((Activity) context).getLayoutInflater().inflate(layoutCode, parent, false);

        holder = new ViewHolder();
        assert view != null;


        holder.chkLike=(CheckBox) view.findViewById(R.id.chkLike);

        view.setTag(holder);
     } else {
        holder = (ViewHolder) view.getTag();
     }


    holder.chkLike.setChecked(entity.IsLiked()); 

    return view;
}
class ViewHolder { 
    CheckBox chkLike;
}
}

主要活动

public class Main extends Activity{
    EntityAdapter adapter;
    GridView gridView  = null;


   public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
       ArrayList<Entity> arraylist = EntityHelper.fetch("select * from entity",this);


      adapter = new EntityAdapter(this, R.layout.item_grid_image, arraylist);


       gridView.setAdapter(adapter);

     gridView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                long arg3) {

             adapter.getItem(pos).setLiked(true);
             adapter.notifyDataSetChanged();


        }


    });
}