2015-01-31 75 views
-1

您好!簡單的購物清單應用程序(具有自定義行的ListView,自定義適配器)。剛剛處理着名的listview複選框滾動問題。。保存數據

請檢查我的代碼(正確的viewHolder實現),並幫我找到最簡單的方法來保存數據。 (之後的onDestroy())

適配器:

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; 
} 

}

回答