Android - Remove GridView item from inside getView()? - android

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!

Related

ListView always deletes last row from CustomAdaptor

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

How to refresh the disabled ListView

I need help to refresh the ListView of disabled item. I've read a few articles, I gotta say I have no idea how to refresh the disabled item, therefore if you can give me a hand and post with that additional desired code, it would be more than appreciated.
Thanks in advance!
I have this code in my Activity:
adapter = new CustomAdapter(PendingOrdersActitvity.this, itemsList1);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
for (int i = 0; i <itemsList1.size(); i++) {
if(i == position){
view.setEnabled(false);
view.setClickable(false);
view.setBackgroundColor(Color.parseColor("#DCDBDB"));
ItemsBean bean = new ItemsBean();
bean.setInvNo(itemsList1.get(position).getInvNo());
bean.setItemnNameDisplay(itemsList1.get(position).getItemnNameDisplay());
bean.setQuantityDisplay(itemsList1.get(position).getQuantityDisplay());
bean.setProdnum(itemsList1.get(position).getProdnum());
newlist.add(bean);
adapter.getmethod(position);
}
}
insertintodatabase(newlist);
newlist.clear();
adapter.notifyDataSetChanged();
return true;
}
});
This is my custom Adapter class I don't know where is fault but i need help to complete the project as am new to android
public class CustomAdapter extends BaseAdapter {
Context ctx;
private int pos;
LayoutInflater inflator;
ArrayList<ItemsBean> newList = new ArrayList<ItemsBean>();
ArrayList<ItemsBean> newListitems = new ArrayList<ItemsBean>();
ArrayList<String> childList = new ArrayList<String>();
ArrayList<String> qtychildList = new ArrayList<String>();
String parentobjid=null;
PendingOrdersActitvity myactivity;
public CustomAdapter(PendingOrdersActitvity kdsActitvity, ArrayList<ItemsBean> invoiceDataList) {
this.ctx = kdsActitvity;
this.newList = invoiceDataList;
this.inflator = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
pos = -1;
}
public int getCount() {
return newList.size();
}
public void getmethod(int pos1) {
pos = pos1;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public static class ViewHolder {
TextView qty, name, childText, qtyChild;
}
#SuppressLint("NewApi") #Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
String item = null, qty = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflator.inflate(R.layout.invoicelistadapter, null);
holder.qty = (TextView) convertView.findViewById(R.id.qty);
holder.name = (TextView) convertView.findViewById(R.id.item);
holder.childText = (TextView) convertView
.findViewById(R.id.childitem);
holder.qtyChild = (TextView) convertView
.findViewById(R.id.qtychild);
convertView.setTag(holder);
} else {
if(pos!=-1 && pos==position)
{
convertView.setEnabled(false);
convertView.setClickable(false);
convertView.setBackgroundColor(Color.parseColor("#DCDBDB"));
}
holder = (ViewHolder) convertView.getTag();
}
//holder.qty.setText(String.valueOf(newList.get(position).getQuantityDisplay()));
parentobjid=newList.get(position).getParentobjectid();
if(!parentobjid.isEmpty())
{
holder.name.setText(" " +newList.get(position).getItemnNameDisplay());
holder.name.setTextColor(Color.parseColor("#CC0000"));
holder.qty.setText(" "+String.valueOf(newList.get(position).getQuantityDisplay()));
holder.qty.setTextColor(Color.parseColor("#CC0000"));
} else {
holder.name.setText(newList.get(position).getItemnNameDisplay());
holder.qty.setText(String.valueOf(newList.get(position)
.getQuantityDisplay()));
holder.name.setTextColor(Color.parseColor("#FFFFFF"));
holder.qty.setTextColor(Color.parseColor("#FFFFFF"));
}
}
}
call adapter.notifyDataSetChanged() inside the listview ClickListener.
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
for (int i = 0; i <itemsList1.size(); i++) {
if(i == position){
view.setEnabled(false);
view.setClickable(false);
view.setBackgroundColor(Color.parseColor("#DCDBDB"));
ItemsBean bean=new ItemsBean();
bean.setInvNo(itemsList1.get(position).getInvNo());
bean.setItemnNameDisplay(itemsList1.get(position).getItemnNameDisplay());
bean.setQuantityDisplay(itemsList1.get(position).getQuantityDisplay());
bean.setProdnum(itemsList1.get(position).getProdnum());
newlist.add(bean);
adapter.getmethod(position);
}
insertintodatabase(newlist);
newlist.clear();
adapter.notifyDataSetChanged();
return true;
}
});
The ListView is just a container.
Instead of enabling the single items, clear it and recreate it through your Adapter.
In fact the adapter just ties the ListView to an ArrayList of elements and represents into the ListView the "state" of the ArrayList.
Do not operate to ListView already created, but refresh the ArrayList and the ListView will be refreshed too!
use notifydatasetchanged();
Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself

ListView adapter behaves strangely

ListView adapter does strange things. Method getChecked() (adapter code shown below) does not return the value that I expect. As if he is late by one step.
For understanding, I will explain: I am using a custom ListView, every item contain one CheckBox (and other Views). I want to make when I press the button to show the position of the checked elements. This makes the method getChecked().
But the following happens: I check the 2nd and the 4th list items and click on the button, the result - [], then I check the 5th item, the result - [2, 4], then I clean all CheckBoxes, result [2, 4, 5] when I click the button again, I receive - []. Result is late by one step.
public class ContactAdapter extends BaseAdapter {
private LayoutInflater inflater;
private ArrayList<Contact> contacts;
private boolean isCheckBoxVisible;
private View view;
private int[] colors = {Color.BLACK, Color.BLUE, Color.RED, Color.GRAY, Color.GREEN};
private int currentMaleColor;
private int currentFemaleColor;
public ContactAdapter(Context context, ArrayList<Contact> contacts) {
this.contacts = contacts;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
isCheckBoxVisible = false;
setColors();
}
#Override
public int getCount() {
return contacts.size();
}
#Override
public Object getItem(int position) {
return contacts.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private Contact getContact(int position) {
return (Contact) getItem(position);
}
public void setCheckBoxVisibility(boolean isVisible) {
isCheckBoxVisible = isVisible;
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.contact_item, parent, false);
}
CheckBox cb = (CheckBox) view.findViewById(R.id.lv_box);
if (isCheckBoxVisible) {
cb.setVisibility(View.VISIBLE);
} else {
cb.setVisibility(View.INVISIBLE);
}
Contact c = getContact(position);
((TextView) view.findViewById(R.id.lv_name)).setText(c.getName() + " " + c.getSurname());
((ImageView) view.findViewById(R.id.lv_img)).setImageBitmap(c.getPhoto());
if (c.getSex().equals("Man")) {
view.setBackgroundColor(currentMaleColor);
} else {
view.setBackgroundColor(currentFemaleColor);
}
boolean isCheck = ((CheckBox) view.findViewById(R.id.lv_box)).isChecked();
contacts.get(position).setChecked(isCheck);
return view;
}
public ArrayList<Integer> getChecked() {
notifyDataSetChanged();
ArrayList<Integer> IDs = new ArrayList<Integer>();
for (Contact c : contacts) {
if (c.isChecked()) IDs.add(c.getID());
}
return IDs;
}
private void setColors() {
int colorM = Integer.parseInt(MainActivity.sp.getString("lp_colorM", "0"));
int colorW = Integer.parseInt(MainActivity.sp.getString("lp_colorW", "0"));
currentMaleColor = colors[colorM];
currentFemaleColor = colors[colorW];
}
}
In my activity I use my adapter, like so:
#Override
protected void onResume() {
super.onResume();
adapter = new ContactAdapter(getApplicationContext(), contacts);
list.setAdapter(adapter);
}
My button's code:
ArrayList<Integer> al = adapter.getChecked();
Toast.makeText(this, al.toString(), Toast.LENGTH_LONG).show();
What do you think about this? I will be glad of any help.
Try to get State of view if convertView == null
if (convertView == null) {
holder = new Holder();
convertView = mInflator.inflate(R.layout.row_viewproduct, null);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
// set the data to view from holder
This is not the answer but want say you can use below
private void setColors() {
int colorM = Integer.parseInt(MainActivity.sp.getString("lp_colorM", "0"));
int colorW = Integer.parseInt(MainActivity.sp.getString("lp_colorW", "0"));
if(colorM < 5){
currentMaleColor = colors[colorM];
}
if(colorW < 5){
currentFemaleColor = colors[colorM];
}
}
To answer your question look at the view holder pattern
http://ricston.com/blog/optimising-listview-viewholder-pattern/
On the advice of njzk2, I changed it:
boolean isCheck = ((CheckBox) view.findViewById(R.id.lv_box)).isChecked();
contacts.get(position).setChecked(isCheck);
At this:
CheckBox checkBox = (CheckBox) view.findViewById(R.id.lv_box);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
contacts.get(position).setChecked(isChecked);
}
});
Now it works :)

Custom NumberPicker buttons.onClickListener

One of my activities requires a list view with custom number pickers in each row.
I created the number picker as suggested here. When I click on the buttons, however, the counter doesn't increment or decrement at all.
The following is the code found at my Custom ListView Adapter.
public class MaterialListViewAdapter extends BaseAdapter
{
ViewHolder holder;
int counter = 0;
private ArrayList<MaterialClass> data;
public static LayoutInflater inflater = null;
public static Dialog dialog;
String materialName;
public MaterialListViewAdapter(Context applicationContext,
int materialdialogcontent, ArrayList<MaterialClass> materials)
{
this.data = materials;
inflater = (LayoutInflater)applicationContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount()
{
return data.size();
}
#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)
{
View vi = convertView;
//ViewHolder holder = new ViewHolder();
if(vi == null)
{
holder = new ViewHolder();
vi = inflater.inflate(R.layout.materialdialogcontent, null);
//Initialize Buttons and TextViews.
holder.num.setText("0");
holder.add.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
counter++;
holder.num.setText("" + counter);
}
});
holder.sub.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
counter--;
holder.sub.setText("" + counter);
}
});
//holder.pk = (NumberPicker)vi.findViewById(R.id.npMaterialAmount);
vi.setTag(holder);
}
else
{
holder = (ViewHolder)vi.getTag();
}
holder.txt.setText(data.get(position).getName());
//holder.pk.setMaxValue(20);
//holder.pk.setMinValue(0);
return vi;
}
private class ViewHolder
{
TextView txt;
Button add;
Button sub;
TextView num;
//NumberPicker pk;
}
}
When I try debugging to see what's going on, counter doesn't even initialize with '0'.
I tried initializing the counter in the getView() method, however in order to do so I need to set the counter to final, and then another error shows up saying
The final local variable counter cannot be assigned, since it is defined in an enclosing type.
Any suggestions?
Updated for additional code:
public class Material extends Activity
{
ArrayList<String> materialList;
ListView lv;
Button btnConfirm;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_material);
lv = (ListView)findViewById(R.id.list);
btnConfirm = (Button)findViewById(R.id.btnConfirm);
materialList = new ArrayList<String>();
Intent i = getIntent();
materialList = i.getStringArrayListExtra("materialList");
if(materialList != null)
{
Toast t = Toast.makeText(getApplicationContext(), materialList.get(0).toString(), Toast.LENGTH_LONG);
t.show();
}
else
{
//FILL HERE LATER
}
ArrayList<MaterialClass> materials = new ArrayList<MaterialClass>();
for(String temp : materialList)
{
MaterialClass m = new MaterialClass();
m.setName(temp);
materials.add(m);
}
MaterialListViewAdapter adapter = new MaterialListViewAdapter(getApplicationContext(), R.layout.materialdialogcontent, materials);
lv.setAdapter(adapter);
}
}
You should implement the onItemClickListener for your listView . You are using listener in adapter class but practically those numbers are nothing but items of that listView, so that to operate on those buttons (listView's items) you've not defined onItemClickListener. So after setting adapter write
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View item, int position, long id) {
// here you are getting position of clicked item
}
}
UPDATE:
I've gone through your code again and I found these:
1.you are writing this line:
MaterialListViewAdapter adapter = new MaterialListViewAdapter(getApplicationContext(), R.layout.materialdialogcontent, materials);
but I didn't see any constructor in your Adapter.
2.As you are extending BaseAdapter, you must override getCount() , getItem(int position) and getItemId(int position) method as like getView() . There you are getting issue.
Try this :
public class MaterialListViewAdapter extends BaseAdapter
{
ViewHolder holder;
int counter = 0;
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View vi = convertView;
//ViewHolder holder = new ViewHolder();
if(vi == null)
{
holder = new ViewHolder();
vi = inflater.inflate(R.layout.materialdialogcontent, null);
//Initialize Buttons and TextViews.
//holder.pk = (NumberPicker)vi.findViewById(R.id.npMaterialAmount);
vi.setTag(holder);
}
else
{
holder = (ViewHolder)vi.getTag();
}
holder.txt.setText(data.get(position).getName());
//holder.pk.setMaxValue(20);
//holder.pk.setMinValue(0);
holder.add.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
counter++;
holder.num.setText("" + counter);
}
});
holder.sub.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
counter--;
holder.num.setText("" + counter);
}
});
return vi;
}
private class ViewHolder
{
TextView txt;
Button add;
Button sub;
TextView num;
//NumberPicker pk;
}
}

Android - Gridview, custom layout onclicklistener

I have a GridView with two TextViews inside it, When the GridView is populated, an OnClickListener is set which returns the position of the item that was selected. I want to trigger a method when one of the TextViews is selected.
Is this possible? If yes, how do I set this up?
EDIT 3:
Inside my activity whch populated the GridView: I retrieve a String-Array from my Strings.xml, a for loop examines each item inside the Array and searches for a condition based on the Item's name inside the SharedPreferences, this for loop is solely for counting how many "true" conditions there are, so it retrieves a int saved inside the count. Then a new String[] is created, this required an exact length to be given before items can be added to it, so I check count if it's more than 0, it will give the String[] a length of count and then another for loop will add each true to the String[] list that we just created. If count is 0 (no true conditions found in the first for loop) then only 1 Item is added to the String[] and is given the value "No Favourites Added".
Then you have the GridView's OnItemClickListener().
String s[] = getResources().getStringArray(R.array.FullList);
int count = 0;
for(int i = 0; i < s.length; i++) {
SharedPreferences sP = getActivity().getSharedPreferences("fav", MODE_PRIVATE);
Boolean b = sP.getBoolean(s[i], false);
if (b == true) {
count++;
}
}
String[] newList;
if (count > 0) {
newList = new String[count];
count = 0;
for(int i = 0; i < s.length; i++) {
SharedPreferences sP = getActivity().getSharedPreferences("fav", MODE_PRIVATE);
Boolean b = sP.getBoolean(s[i], false);
if (b == true) {
newList[count] = s[i];
count++;
}
}
} else {
newList = new String[1];
newList[0] = "No favourites added";
}
GridView FavGV = (GridView) getActivity().findViewById(R.id.sexp_fav);
FavGV.setAdapter(new Tab01_FavAdapter(getActivity(), newList));
FavGV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView arg0,
View arg1, int position, long arg3) {
//Intent i = new Intent(getActivity(), PosPreview_Gestures.class);
//i.putExtra("position", position);
//startActivity(i);
}
});
So that's the code inside the Activity which populates the GridView. The Adapter in it's original, functioning form: This simply populates the GridView with Favourite Items (their names from the String[]) and adds a TextView with "Remove" which when pressed, shows a Toast: "Remove".
public class Tab01_FavAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflator;
String mEntries[];
public Tab01_FavAdapter (Context c, String[] entries) {
mContext = c;
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) {
if(convertView == null) {
convertView = mInflator.inflate(R.layout.favitemlayout, parent, false);
}
TextView tx = (TextView) convertView.findViewById(R.id.favgridremoveitem);
OnClickListener oCL = new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext,"Remove",Toast.LENGTH_SHORT).show();
}
};
tx.setOnClickListener(oCL);
return convertView;
}
}
I am assuming that you are using a custom adapter for populating this GridView, and passing the Context as an argument to the constructor.
In the custom adapter, you should add onClickListeners to the TextViews. Using the context, you can call methods from your activity:
((CallingActivityName)context).methodYouWishToCall(parameters);
This would go inside the onClickListeners.
Edit: Added some code:
public class MyGridAdapter extends BaseAdapter {
private final List<MyObjectClass> mEntries;
private final LayoutInflater mInflater;
private final Context mContext;
public static class ViewHolder {
public TextView tx;
}
public MyGridAdapter(CallingActivityName context, List<MyObjectClass> entries) {
super();
mEntries = entries;
mContext = context;
mInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mEntries.size();
}
#Override
public Object getItem(int position) {
return mEntries.get(position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflator.inflate(R.layout.favitemlayout, parent, false);
holder = new ViewHolder();
holder.tx = (TextView) convertView
.findViewById(R.id.favgridremoveitem);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final MyObjectClass info = mEntries.get(position);
holder.tx.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((CallingActivityName)mContext).favRemove(info);
notifyDataSetChanged();
}
});
return convertView;
}
}
So, CallingActivityName is the name of the Activity where you initiate the adapter and where the method you need to call resides. info is the object held at position position of the gridview. MyObjectClass is the class name of the objects in the List mEntries.

Categories

Resources