Android - Remove GridView item from inside getView()?

前端 未结 2 1979
逝去的感伤
逝去的感伤 2021-01-17 05:22

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:

Activi

相关标签:
2条回答
  • 2021-01-17 06:17

    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!

    0 讨论(0)
  • 2021-01-17 06:18

    This is what I did, there was no need to initialise the 'adapter' variable. Inside the getView() simply do this:

    1. 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
    
    0 讨论(0)
提交回复
热议问题