I have a ListView in AlertDialog which contains more button on each row & it will popup a list with delete option. When I click on delete option, its deleting the last item. In CustomAdaptor I tried a notifyDataSetChanged() after deleting item from ArrayList. Here it always deletes the last item irrespective of item position.
CustomAdaptor Code
public class CustomAdapter extends BaseAdapter {
Context context;
List<String> lrowItems ;
ArrayList<String> listItems;
String className;
CalHelper calHelper;
Settings settings;
LayoutInflater inflter;
public CustomAdapter(Context applicationContext, ArrayList<String> listItems) {
this.context = applicationContext;
this.listItems = listItems;
this.className = context.getClass().getSimpleName();
this.calHelper = new CalHelper(applicationContext);
this.settings = new Settings(applicationContext);
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
if(listItems != null) {
return listItems.size();
}else{
return 0;
}
}
#Override
public Object getItem(int position) {
return listItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
//With following overrides Prevent listview item will not mix randomly
//and convertView provided is of the appropriate type.
#Override
public int getViewTypeCount() {
if(getCount() > 0){ //for no records in returning view
return getCount();
}else{
return super.getViewTypeCount();
}
}
#Override
public int getItemViewType(int position) {
return position;
}
/* private view holder class for holding calculation history*/
private class HistoryViewHolder {
TextView more;
TextView expression;
TextView result;
TextView shortNote;
TextView expTime;
}
/* private view holder class for holding GST calculations history*/
private class GstHistoryViewHolder {
TextView amount;
TextView gst;
TextView total;
TextView expTime;
ImageView share;
}
/* private view holder class */
private class BMIViewHolder {
TextView bmiScore;
TextView bmiDate;
TextView bmiWeight;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
//final int pos = position;
if(className.equals("MainActivity")) {
final HistoryViewHolder holder = new HistoryViewHolder();
final String expString = listItems.get(position);
final String expre = expString.substring(0, expString.indexOf(":"));
final String expreTime = expString.substring(expString.indexOf(":") + 1, expString.length());
final String result = expre.substring(expre.indexOf("=")+1);
String timePattern = calHelper.calHistoryTimePattern(expreTime);
SimpleDateFormat localDateFormat = new SimpleDateFormat(timePattern);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listview_row, null);
holder.more = (TextView) convertView
.findViewById(R.id.more);
holder.expression = (TextView) convertView.findViewById(R.id.expression);
holder.result = (TextView) convertView.findViewById(R.id.result);
holder.shortNote = (TextView) convertView.findViewById(R.id.shortNote);
holder.expTime = (TextView) convertView.findViewById(R.id.expTime);
holder.expression.setText(expre.substring(0, expre.indexOf("=")));
holder.result.setText(result);
String time = localDateFormat.format(new Date(expreTime));
holder.expTime.setText(time);
holder.shortNote.setText(settings.getHistoryNote(context,expString));
convertView.setTag(holder);
final TextView btnMore = (TextView) holder.more;
btnMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPopup(v, position, expString, expre, expreTime, holder.shortNote);
}
});
}
}
return convertView;
}
public void showPopup(View v, final int position, final String expString, final String expression, final String expTime, final TextView shortNote) {
final PopupMenu popup = new PopupMenu(context, v);
//truncate title with ellipsis for more characters
final String noteTitle = expression.length()>10? expression.substring(0, 10) + "..." : expression;
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.history_menu, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Intent intent = new Intent(context, MainActivity.class);
int itenId = item.getItemId();
switch (itenId){
case R.id.mnuInsertExpression:
//some code here
break;
case R.id.mnuHisNote:
//some code here
break;
case R.id.mnuCopyHisRecord:
calHelper.copyToClipboard(expression);
break;
case R.id.mnuShareHisRecord:
calHelper.shareText(expression);
break;
case R.id.mnuDeleteHisRecord: //This is where I am deleting item
System.out.println("Pos:"+position);
listItems.remove(position);
notifyDataSetChanged();
Collections.reverse(listItems); //sort descending by time again
settings.clearSharedPre(context,expString); //remove note attached to this expression from ShredPref
settings.saveArrayList(context, listItems, "EXP_HISTORY");
intent.putExtra("HISTORY_RECORD_DELETED", true);
Toast.makeText(context,"Record removed from history", Toast.LENGTH_SHORT).show();
context.startActivity(intent);
break;
}
return true;
}
});
popup.show();
}
Any help is greatly appreciated.
Try this getView():
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
HistoryViewHolder holder;
if(className.equals("MainActivity")) {
final String expString = listItems.get(position);
final String expre = expString.substring(0, expString.indexOf(":"));
final String expreTime = expString.substring(expString.indexOf(":") + 1, expString.length());
final String result = expre.substring(expre.indexOf("=")+1);
String timePattern = calHelper.calHistoryTimePattern(expreTime);
SimpleDateFormat localDateFormat = new SimpleDateFormat(timePattern);
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.listview_row, null);
holder = new HistoryViewHolder();
holder.more = (TextView) convertView.findViewById(R.id.more);
holder.expression = (TextView) convertView.findViewById(R.id.expression);
holder.result = (TextView) convertView.findViewById(R.id.result);
holder.shortNote = (TextView) convertView.findViewById(R.id.shortNote);
holder.expTime = (TextView) convertView.findViewById(R.id.expTime);
holder.more.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = (int) v.getTag();
showPopup(v, pos, expString, expre, expreTime, holder.shortNote);
}
});
}else{
holder = (HistoryViewHolder)convertView.getTag();
}
holder.expression.setText(expre.substring(0, expre.indexOf("=")));
holder.result.setText(result);
String time = localDateFormat.format(new Date(expreTime));
holder.expTime.setText(time);
holder.shortNote.setText(settings.getHistoryNote(context, expString));
holder.more.setTag(position);
convertView.setTag(holder);
}
return convertView;
}
Hope that helps!
Its because you are using the position of the getView parameter, that will always be whatever the last index is at the time you go to use it.
Instead you need to add that position to the view, possibly in your convertView is what I usually do (the tag can be anything you want), do convertView.setTag(position) in your getView method as you are creating each items view, and then in your delete method within showpopup you can do (int)view.getTag() to get the position to remove from your dataset.
You should add the postion to the button using setTag() and get the position when passing it to showPopup() using getTag(). You can do the following.
// ....
final TextView btnMore = (TextView) holder.more;
btnMore.setTag(position); // here add the position to the button using setTag().
btnMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// here you can get position your button using v.getTag().
int pos = (int) v.getTag();
showPopup(v, pos, expString, expre, expreTime, holder.shortNote);
}
});
Related
Because it repeats the product counter which is a TextView; I have the following scenario:
The user selects the product, and applies the quantity.
From the Activity and not from the Adapter I show the quantity of the selected product as seen in the image.
Everything works perfect, until under the screen and the counter magically passes to another product, I have implemented these methods by suggestion:
#Override
public long getItemId(int position)
{
return position;
}
#Override
public int getItemViewType(int position)
{
return position;
}
and still I still get this error. I have also tried to modify the counter from the Adapter but the same thing happens. I want that counter to stay fixed and not update when under the screen.
Adapter:
public class ProductoAdapter extends BaseAdapter
{
private Activity activity;
private LayoutInflater inflater;
private ArrayList<Producto> listadoProductos;
private ArrayList<Producto> productosPedidos;
Producto producto;
Empresas pedido;
public final int TYPE_NOTICIA=0;
public final int TYPE_LOAD=1;
private gestionSharedPreferences sharedPreferences;
private Context context;
/*
OnLoadMoreListener loadMoreListener;
*/
boolean isLoading=false, isMoreDataAvailable=true;
vars vars;
public static int contador;
public static int i;
public static int contadorGeneral;
private NumberFormat numberFormat;
ImageLoader imageLoader = ControllerSingleton.getInstance().getImageLoader();
public ProductoAdapter(Activity activity, ArrayList<Producto> listadoProductos)
{
this.activity=activity;
this.listadoProductos=listadoProductos;
productosPedidos=new ArrayList<Producto>();
vars=new vars();
sharedPreferences=new gestionSharedPreferences(this.activity);
contador=0;
contadorGeneral=0;
producto=new Producto();
/* LocalBroadcastManager.getInstance(context).registerReceiver(mMessageReceiver,
new IntentFilter("custom-message"));*/
}
/* public BroadcastReceiver mMessageReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
// Get extra data included in the Intent
producto = (Producto) intent.getSerializableExtra("producto");
Toast.makeText(context, producto.getNombreProducto()+producto.getNumeroDeProducto() ,Toast.LENGTH_SHORT).show();
}
};*/
#Override
public int getCount()
{
return listadoProductos.size();
}
#Override
public Producto getItem(int position)
{
return listadoProductos.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public int getItemViewType(int position)
{
return position;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup)
{
numberFormat = NumberFormat.getNumberInstance(Locale.GERMAN);
if (view == null)
{
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.producto_row_layout, viewGroup, false);
Log.i("martin","null");
}
else
{
Log.i("martin","llenoooooooooo");
}
final Producto producto = getItem(position);
ImageView imagenProducto = (ImageView) view.findViewById(R.id.imagenProducto);
TextView nombreProducto = (TextView) view.findViewById(R.id.nombreProducto);
TextView cantidadProducto = (TextView) view.findViewById(R.id.cantidadProducto);
TextView precioGeneralProducto = (TextView) view.findViewById(R.id.precioGeneralProducto);
TextView precioPideProducto = (TextView) view.findViewById(R.id.precioPideProducto);
TextView ahorroProducto = (TextView) view.findViewById(R.id.ahorroProducto);
if (producto.getImagenProducto().toString().equals("http://fasttrackcenter.com/pide/app/"))
{
imagenProducto.setImageResource(R.drawable.ic_not_image_found);
}
else
{
Glide.with(activity).
load(producto.getImagenProducto().toString()).
thumbnail(0.5f).into(imagenProducto);
}
nombreProducto.setText(producto.getNombreProducto()+" x "+producto.getCantidadProducto()+" "+producto.getUnidadProducto());
//cantidadProducto.setText(producto.getCantidadProducto());
precioGeneralProducto.setText("$"+numberFormat.format(Double.parseDouble(producto.getPrecioGeneralProducto())));
precioGeneralProducto.setPaintFlags(precioGeneralProducto.getPaintFlags()| Paint.STRIKE_THRU_TEXT_FLAG);
precioPideProducto.setText("$"+numberFormat.format(Double.parseDouble(producto.getPrecioPideProducto())));
int valorahorro=(Integer.parseInt(producto.getPrecioGeneralProducto()))-(Integer.parseInt(producto.getPrecioPideProducto()));
ahorroProducto.setText(""+"$"+numberFormat.format(Double.parseDouble(""+valorahorro)));
return view;
}
}
Activity:
I use a TextView as a counter which is initially invisible, but when it is selected, it is visible with the quantity of product selected.
From the activity I use this method:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Producto producto = (Producto) parent.getItemAtPosition(position);
final View contadorImagenProductoBolsa = Pedidos.this.findViewById(R.id.contadorProductoImagenBolsa);
TextView test1TextView = (TextView) view.findViewById(R.id.contadorProductoImagenBolsa);
mostrarDialogoDetalle(test1TextView,position,producto.getIdProducto(),producto.getImagenProducto(), producto.getNombreProducto(),
producto.getCantidadProducto(),producto.getUnidadProducto(), producto.getPrecioGeneralProducto(),producto.getPrecioPideProducto(),
producto.getAhorroProducto());
}
Has anyone had this happen? how did they solve it?
Here it is perfect, but when I go under the screen and I go back and up, observe how the counter happens to another product inexplicably:
I want an effective help and a possible snippet if it is the case of an incorrect adapter or activity.
Thank you.
I think You have to add ViewHolder For ProductoAdapter Like:
class ViewHolder
{
TextView nombreProducto,cantidadProducto
,precioGeneralProducto,precioPideProducto,ahorroProducto;
ImageView imagenProducto;
public ViewHolder(View view){
imagenProducto = (ImageView) view.findViewById(R.id.imagenProducto);
nombreProducto = (TextView) view.findViewById(R.id.nombreProducto);
cantidadProducto = (TextView) view.findViewById(R.id.cantidadProducto);
precioGeneralProducto = (TextView) view.findViewById(R.id.precioGeneralProducto);
precioPideProducto = (TextView) view.findViewById(R.id.precioPideProducto);
ahorroProducto = (TextView) view.findViewById(R.id.ahorroProducto);
}
}
Use setTag and getTag For ViewHolder Like:
ViewHolder holder;
if (view == null)
{
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.producto_row_layout, viewGroup, false);
holder = new ViewHolder();
Log.i("martin","null");
}
else
{ holder = (ViewHolder) view.getTag();
Log.i("martin","llenoooooooooo");
}
final Producto producto = getItem(position);
if (producto.getImagenProducto().toString().equals("http://fasttrackcenter.com/pide/app/"))
{
holder.imagenProducto.setImageResource(R.drawable.ic_not_image_found);
}
else
{
Glide.with(activity).
load(producto.getImagenProducto().toString()).
thumbnail(0.5f).into(holder.imagenProducto);
}
holder.nombreProducto.setText(producto.getNombreProducto()+" x "+producto.getCantidadProducto()+" "+producto.getUnidadProducto());
.
.
.
view.setTag(holder);
return view;
i hope this is help you
I'm trying to add separators between my list view items, I have sorted them into date order and added list entries where the separator needs to go but as soon as it gets to a seperator it stops, no error message or anything it just doesn't add the seperator. I've added breakpoints and it definitely runs the code to add it but it doesn't show up. Even if there are other items to add after the separator it still stops at the separator.
code:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater itemInflater = LayoutInflater.from(getContext());
JourneyItem singleItem = list.get(position);
if(singleItem.isSeperator()){
//set customRow to seperator layout
View customRow = itemInflater.inflate(R.layout.journey_list_seperator, parent, false);
TextView monthText = (TextView) customRow.findViewById(R.id.seperatorMonthText);
TextView yearText = (TextView) customRow.findViewById(R.id.seperatorYearText);
Date current = new Date();
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String dtp = GeneralUtil.SQLDateFormatToHuman(list.get(position).getDepartDateTime());
try {
current = df.parse(dtp);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat sdfDate = new SimpleDateFormat("MMMM");
monthText.setText(sdfDate.format(current));
yearText.setText(list.get(position).getDepartDateTime().substring(6,10));
return customRow;
}else {
View customRow = itemInflater.inflate(R.layout.custom_journeyitem_row, parent, false);
TextView titleText = (TextView) customRow.findViewById(R.id.titleDisplay);
TextView fromText = (TextView) customRow.findViewById(R.id.fromLocationDisplay);
TextView departText = (TextView) customRow.findViewById(R.id.departDateTimeDisplay);
TextView toText = (TextView) customRow.findViewById(R.id.toLocationDisplay);
TextView colourLbl = (TextView) customRow.findViewById(R.id.colourDisplay);
titleText.setText(singleItem.getTitle());
fromText.setText("From: " + singleItem.getFromLocation());
departText.setText(singleItem.getDepartDateTime());
toText.setText("To: " + singleItem.getToLocation());
colourLbl.setBackgroundColor(singleItem.getColourCode());
return customRow;
}
Create Coustom adapter like this.
class CustomAdapter extends BaseAdapter {
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private ArrayList<String> mData = new ArrayList<String>();
private TreeSet<Integer> sectionHeader = new TreeSet<Integer>();
private LayoutInflater mInflater;
public CustomAdapter(Context context) {
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(final String item) {
mData.add(item);
notifyDataSetChanged();
}
public void addSectionHeaderItem(final String item) {
mData.add(item);
sectionHeader.add(mData.size() - 1);
notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
return sectionHeader.contains(position) ? TYPE_SEPARATOR : TYPE_ITEM;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public String getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int rowType = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
switch (rowType) {
case TYPE_ITEM:
convertView = mInflater.inflate(R.layout.snippet_item1, null);
holder.textView = (TextView) convertView.findViewById(R.id.text);
break;
case TYPE_SEPARATOR:
convertView = mInflater.inflate(R.layout.snippet_item2, null);
holder.textView = (TextView) convertView.findViewById(R.id.textSeparator);
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(mData.get(position));
return convertView;
}
public static class ViewHolder {
public TextView textView;
}
}
Complete link here.
Can you give me an example of passing data from ListView to another ListView.
For example I have my MainActivity.java that has ListView and when i delete item on it. i want to achieve is to pass and add it to another ListView activity.
MainActivity.java | OnitemClick
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String member_name = rowItems.get(position).getMember_name();
int product_icons = rowItems.get(position).getProfile_pic_id();
String status = rowItems.get(position).getStatus();
// passing data
Intent i = new Intent(getBaseContext(), CarActivity.class);
i.putExtra("member_name", member_name);
i.putExtra("product_icons", product_icons);
i.putExtra("status", status);
RowItem item = rowItems.get(position);
rowItems.remove(item);
newadapter = new CustomAdapter(this, rowItems);
mylistview.setAdapter(newadapter);
newadapter.notifyDataSetChanged();
Toast.makeText(this.getApplicationContext(),
"Added to Cart: " + member_name, Toast.LENGTH_SHORT).show();
}
CartActivity.java | onCreate
Bundle extras = getIntent().getExtras();
if (extras != null) {
String member_names = extras.getString("member_name");
int product_icons = extras.getInt("product_icons");
String status = extras.getString("status");
}
rowItems = new ArrayList<RowItem_cart>();
RowItem_cart item = new RowItem_cart(member_names, product_icons, status);
rowItems.add(item);
mylistview = (ListView) findViewById(R.id.list);
mylistview.setItemsCanFocus(true);
//
final CustomerAdapter_Cart adapter = new CustomerAdapter_Cart(this,
rowItems);
mylistview.setAdapter(adapter);
mylistview.setOnItemClickListener(this);
mylistview.setScrollingCacheEnabled(false);
mylistview.invalidateViews();
CustomAdapter_cart
public class CustomerAdapter_Cart extends BaseAdapter {
Context context;
List<RowItem_cart> rowItems;
public CustomerAdapter_Cart(Context context, List<RowItem_cart> rowItems) {
this.context = context;
this.rowItems = rowItems;
}
public CustomerAdapter_Cart() {
// TODO Auto-generated constructor stub
}
#Override
public int getCount() {
return rowItems.size();
}
#Override
public Object getItem(int position) {
return rowItems.get(position);
}
#Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
/* private view holder class */
private class ViewHolder {
ImageView product_icons;
TextView member_name;
TextView status;
Button addtocart;
EditText txtQuantity;
TextView lblQty;
}
ViewHolder holder = null;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_cart, null);
holder = new ViewHolder();
holder.member_name = (TextView) convertView
.findViewById(R.id.member_name);
holder.product_icons = (ImageView) convertView
.findViewById(R.id.product_icons);
holder.status = (TextView) convertView.findViewById(R.id.status);
holder.addtocart = (Button) convertView
.findViewById(R.id.btnaddtocart);
holder.txtQuantity = (EditText) convertView
.findViewById(R.id.txtQuantity);
holder.lblQty = (TextView) convertView.findViewById(R.id.lblQty);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
RowItem_cart row_pos = rowItems.get(position);
holder.product_icons.setImageResource(row_pos.getProfile_pic_id());
holder.member_name.setText(row_pos.getMember_name());
holder.status.setText(row_pos.getStatus());
holder.addtocart.setText(" add to cart");
return convertView;
}
}
RowItem_cart
public class RowItem_cart {
private String member_name;
private int profile_pic_id;
private String status;
public RowItem_cart(String member_name, int profile_pic_id, String status) {
this.member_name = member_name;
this.profile_pic_id = profile_pic_id;
this.status = status;
}
public String getMember_name() {
return member_name;
}
public void setMember_name(String member_name) {
this.member_name = member_name;
}
public int getProfile_pic_id() {
return profile_pic_id;
}
public void setProfile_pic_id(int profile_pic_id) {
this.profile_pic_id = profile_pic_id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
In your MainActivity you probably have an onItemSelected() listener. In there you can get the item that was removed from the active item list. Assuming you have a field for the deleted items list you would simply call add() on that list with the item you just deleted.
Without some of your actual code that's about as far as we're going to be able to take you ;)
I need a way to remove an Item from the GridView but this must be done from within the getView() method inside my custom Adapter. Here is my GridView:
Activity:
...
String[] newList;
newList[0] = "Item 1";
newList[1] = "Item 2";
newList[2] = "Item 3";
...
GridView GV = (GridView) getActivity().findViewById(R.id.gv);
GV.setAdapter(new Adapter(getActivity(), newList));
GV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView arg0,
View arg1, int position, long arg3) {
...
}
});
Adapter
public class Adapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflator;
private String mEntries[];
public static class ViewHolder {
public TextView myTextView;
}
public Adapter (Context context, String[] entries) {
mContext = context;
mInflator = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mEntries = entries;
}
#Override
public int getCount() {
return mEntries.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null) {
convertView = mInflator.inflate(R.layout.gvitemlayout, parent, false);
holder = new ViewHolder();
holder.myTextView = (TextView) convertView.findViewById(R.list.removeItem);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
String string = mEntries[position];
String[] data = string.split("\\.");
if (data.length < 2) {
TextView itemName = (TextView) convertView.findViewById(R.list.itemName);
itemName.setText("");
TextView itemClass = (TextView) convertView.findViewById(R.favlist.itemClass);
itemClass.setText("");
holder.myTextView.setText("");
TextView itemNone = (TextView) convertView.findViewById(R.list.itemNone);
itemNone.setText("No Items");
} else {
TextView itemName = (TextView) convertView.findViewById(R.list.itemName);
itemName.setText(data[1]);
TextView itemClass = (TextView) convertView.findViewById(R.list.itemClass);
itemClass.setText(data[0]);
}
final int info = (Integer) getItem(position);
holder.myTextView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SharedPreferences sP = mContext.getSharedPreferences("fav", mContext.MODE_PRIVATE);
Boolean b = sP.getBoolean(mEntries[info], false);
if (b == true) {
SharedPreferences.Editor editor = sP.edit();
editor.remove(mEntries[info]);
editor.commit();
// REMOVE ITEM CODE NEEDED HERE
}
}
});
return convertView;
}
}
Hope this makes it easier to understand what I need.
This is what I did, there was no need to initialise the 'adapter' variable. Inside the getView() simply do this:
Remove the Item from the list that was used as the data source.
So. if you want to remove Item 2 from the list
String mEntries[] = ITEM1, ITEM2, ITEM3, etc
Do this:
String newList[] = new String[mEntries.length - 1];
int count = 0;
for (int i = 0; i < mEntries.length; i++) {
if (mEntries.length - 1 > 0) {
if (mEntries[i] == mEntries[1]) { // mEntries[1] as the range starts from 0, so 1 would be ITEM2
// SKIP IF MATCHES THE ITEM YO WANT TO REMOVE
} else {
newList[count] = mEntries[i];
count++;
}
}
}
mEntries = newList; // save the new list into mEntries
notifyDataSetChanged(); // notify the changes and the listview/gridview will update
What you are asking for is very possible. You didn't give enough code for it to be clear exactly what's happening, but the code above you posted won't work unless the remove button is an entire view returned by getView in the adapter.
Your getView in your adapter will need to look something like this:
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.grid_view_item, null);
}
Button removeButton = (Button) convertView.findViewById(R.id.remove_button);
removeButton.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
adapter.mThumbIdsList.remove(position);
adapter.notifyDataSetChanged();
}
});
return convertView;
}
Hope this helps. Good luck!
I have some trouble with layout in my list activity.
My list contain separators and text rows
SetupActivity extend ListActivity
private MyCustomAdapter mAdapter;
TextView selection;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mAdapter = new MyCustomAdapter();
mAdapter.addItem("Help/FAQ");
mAdapter.addSeparatorItem("Connection to Server");
// mAdapter.addItem("Connection");
// mAdapter.addItem("Network");
// mAdapter.addItem("config");
// mAdapter.addItem("User");
// mAdapter.addItem("pass");
// mAdapter.addItem("Email");
// mAdapter.addItem("PlatForm");
mAdapter.addSeparatorItem("Consumption");
// mAdapter.addItem("100%");
mAdapter.addSeparatorItem("Map");
// mAdapter.addItem("Map rotation");
// mAdapter.addItem("auto Zoom");
// mAdapter.addItem("Measure Units");
// mAdapter.addItem("Show Heading");
// mAdapter.addItem("Compass North");*/
mAdapter.addFooterItem(getString(R.string.setup_note_map));
mAdapter.addSeparatorItem("Support");
mAdapter.addItem("About");
/*
* mAdapter.addItem("Contact Us"); mAdapter.addItem("Tutorial");
* mAdapter.addItem("Setup Wizard");
*/
mAdapter.addSeparatorItem("Blogs");
mAdapter.addFooterItem(getString(R.string.setup_note_blogs));
setListAdapter(mAdapter);
// selection = (TextView) findViewById(R.id.text);
}
public void onListItemClick(ListView parent, View view, int position,
long id) {
parent.getChildAt(position).setBackgroundColor(position);
if (position == 0) {
Intent myIntent = new Intent(SetupActivity.this,
WebviewHandlerActivity.class);
myIntent.putExtra("ressource", "help");
SetupActivity.this.startActivity(myIntent);
} else if (position == 6) {
Intent myIntent = new Intent(SetupActivity.this,
AboutActivity.class);
SetupActivity.this.startActivity(myIntent);
}
}
// Adapter Class
private class MyCustomAdapter extends BaseAdapter {
private static final int TYPE_ITEM = 2;
private static final int TYPE_SEPARATOR = 0;
private static final int TYPE_FOOTER = 1;
private static final int TYPE_MAX_COUNT = TYPE_ITEM + 1;
private ArrayList<String> mData = new ArrayList<String>();
private LayoutInflater mInflater;
private TreeSet<Integer> mSeparatorsSet = new TreeSet<Integer>();
private TreeSet<Integer> mFooterSet = new TreeSet<Integer>();
public MyCustomAdapter() {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(final String item) {
mData.add(item);
notifyDataSetChanged();
}
public void addSeparatorItem(final String item) {
mData.add(item);
// save separator position
mSeparatorsSet.add(mData.size() - 1);
notifyDataSetChanged();
}
public void addFooterItem(final String item) {
mData.add(item);
// save separator position
mFooterSet.add(mData.size() - 1);
notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
if (mSeparatorsSet.contains(position))
return TYPE_SEPARATOR;
else if (mFooterSet.contains(position))
return TYPE_FOOTER;
return TYPE_ITEM;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
public int getCount() {
return mData.size();
}
public String getItem(int position) {
return mData.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM:
convertView = mInflater.inflate(R.layout.item1, null);
holder.textView = (TextView) convertView
.findViewById(R.id.text);
break;
case TYPE_SEPARATOR:
convertView = mInflater.inflate(R.layout.item2, null);
holder.textView = (TextView) convertView
.findViewById(R.id.textSeparator);
break;
case TYPE_FOOTER:
convertView = mInflater.inflate(R.layout.footer, null);
holder.textView = (TextView) convertView
.findViewById(R.id.note);
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(mData.get(position));
return convertView;
}
}
public static class ViewHolder {
public TextView textView;
}
my xml item1 & item2 contain a LinearLayout with a TextView inside
and my footer.xml only a textView
My problem is when i click on a row it doesn't get orange to say that i clicked on it except my footer...(the one i don't want)
So i figure out it's because it's not in a LinearLayout so i tried to put off the LinearLayout of item1.xml but i can't compile anymore.
Does someone can explain to me how to get my row with the click Animation and not on my footers ?
Cheers
You are not getting clicked color because you have set a background color `
setBackgroundColor
You need to set a statelistDrawable as background
Edit: You need to set a drwable something like this
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/pressed_img" android:state_pressed="true"/>
<item android:drawable="#drawable/default_img"/>
</selector>