您好!简单的购物清单应用(带自定义行的ListView,自定义适配器)。刚刚着名的listview复选框滚动问题。
请检查我的代码(正确的viewHolder实现)并帮助我找到保存数据的最简单方法。 (在onDestroy()之后)
ADAPTER:
public class ShopAdapter extends BaseAdapter {
private Context mainContex;
private ArrayList<ShopItem> shopItems;
static class ViewHolder {
CheckBox checkBox;
TextView textView;
}
public ShopAdapter(Context mainContex, ArrayList<ShopItem> shopItems) {
this.mainContex = mainContex;
this.shopItems = shopItems;
}
@Override
public int getCount() {
return shopItems.size();
}
@Override
public Object getItem(int position) {
return shopItems.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ShopItem shopItem = shopItems.get(position);
final ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater layoutInflater = LayoutInflater.from(mainContex);
convertView = layoutInflater.inflate(R.layout.shoplist_item, null);
viewHolder.textView = (TextView) convertView.findViewById(R.id.itemTextView);
viewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.doneCheckBox);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.checkBox.setTag(shopItems.get(position));
viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
shopItem.setDone(true);
viewHolder.textView.setTextColor(mainContex.getResources()
.getColor(R.color.done_text_color));
} else {
shopItem.setDone(false);
viewHolder.textView.setTextColor(mainContex.getResources()
.getColor(R.color.secondary_text));
}
}
});
viewHolder.textView.setText(shopItem.getDescription());
viewHolder.checkBox.setChecked(shopItem.isDone());
return convertView;
}
}
项:
public class ShopItem {
private String description;
private boolean done;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isDone() {
return done;
}
public void setDone(boolean done) {
this.done = done;
}
}
答案 0 :(得分:0)
如果要将数据保存到列表视图中,则应使用数据库,建议使用SQLIte。请查看以下链接,获取有关如何操作的简单教程+源代码!
http://androidtuts4u.blogspot.com.br/2013/02/android-list-view-using-custom-adapter.html