Android - Custom ArrayAdapter
Could anybody help me solve my problem. I still trying work with DraggingListView and ArrayAdapter. Now i want realize delete element from listview by click, but when i making : St
Solution 1:
Correct code for adapter:
public class StableArrayAdapter extends ArrayAdapter<Product> {
final int INVALID_ID = -1;
LayoutInflater lInflater;
Context ctx;
public static final String PREFS_NAME = "com.shvedchenko.skleroshop";
public static final String PREFS_THEME = "theme";
HashMap<Product, Integer> mIdMap = new HashMap<Product, Integer>();
public StableArrayAdapter(Context context, int textViewResourceId, List<Product> prod) {
super(context, textViewResourceId, /*objects*/prod);
lInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ctx = context;
for (int i = 0; i < prod.size(); i++) {
mIdMap.put(prod.get(i), i);
}
}
// пункт списка
@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
// используем созданные, но не используемые view
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.item, parent, false);
}
Product p = getItem(position);
SharedPreferences pref = ctx.getSharedPreferences(PREFS_NAME, ctx.MODE_PRIVATE);
int theme = pref.getInt(PREFS_THEME, 0); // getting Integer
if(theme == 0)
((TextView) view.findViewById(R.id.tvDescr)).setTextColor(Color.WHITE);
else
((TextView) view.findViewById(R.id.tvDescr)).setTextColor(Color.BLACK);
((TextView) view.findViewById(R.id.tvDescr)).setText(p.getProductName());
((ImageView) view.findViewById(R.id.ivImage)).setImageResource(p.getProductImage());
ImageView iv = (ImageView)view.findViewById(R.id.ivImage);
iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
StableArrayAdapter.this.remove(getItem(position));
StableArrayAdapter.this.notifyDataSetChanged();
}
});
return view;
}
@Override
public long getItemId(int position) {
if (position < 0 || position >= mIdMap.size()) {
return INVALID_ID;
}
Product item = (Product) getItem(position);
return mIdMap.get(item);
}
@Override
public boolean hasStableIds() {
return true;
}
}
Solution 2:
Remove item from list
list.remove(position);
Then call below method using adapter object.
stableAdapter.notifyData(list);
Write a method in your Adapter class.
public void notifyData(List<Product> prod)
{
//First of all Clear Map
mIdMap.clear();
for (int i = 0; i < prod.size(); ++i) {
mIdMap.put(prod.get(i), i);
}
notifyDataSetChanged();
}
Call this method using adpater object
Post a Comment for "Android - Custom ArrayAdapter"