Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android- Select an item of a GridView programmatically?

I want to perform a click on an item after setAdapter() method.

Consider if you have declared and initialized a Button in your Activity globally then you can perform a click on it programmatically from any scope of that activity and the listener will work. I want something similar like that, to be able to perform a click on any item of my GridView.

So far i have tried all of the below methods one by one but none of them seems to work, i tried different stack questions but not even a single answer worked for me. iconsGrid.setSelection(2);, iconsGrid.setSelected(true);, iconsGrid.performClick();, iconsGrid.performItemClick(iconsGrid, 2, 2);, iconsGrid.performItemClick(iconsGrid, 2, iconsGrid.getItemIdAtPosition(2));,

//Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mTextView = (TextView) findViewById(R.id.txt);
    Integer[] resource_icons = { 
            R.drawable.ic_attachment,
            R.drawable.ic_attachment,
            R.drawable.ic_attachment,
            R.drawable.ic_attachment,
            R.drawable.ic_attachment,
            R.drawable.ic_attachment };

    GridView iconsGrid = (GridView) findViewById(R.id.gv_icons);
    IconGridAdapter iconAdapter = new IconGridAdapter(this, resource_icons);
    iconsGrid.setAdapter(iconAdapter);
   /*
    * I want to perform a click here
    */
}

//Adapter
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater li;
    View grid;
    if (convertView == null) {
        grid = new View(mContext);
        li = ((Activity) mContext).getLayoutInflater();
        grid = li.inflate(R.layout.grid_cell_imageview, parent, false);
    } else {
        grid = (View) convertView;
    }

    ImageView imageView = (ImageView) grid.findViewById(R.id.image);
    imageView.setImageResource(imageId[position]);

    return grid;
}
like image 518
mushahid Avatar asked Dec 25 '22 17:12

mushahid


1 Answers

OK let's do this

declare one field in your adapter say

private int selectedPosition=-1;

now create a setter for this

private void setSelectedPosition(int position)
{
selectedPosition=position;
}

Now in your getView method

if(position==selectedPosition)
    {
    grid.setSelected(true);

    //OR

    grid.setBackgroundColor(<Some Color>);
    }

Now after setting the adapter

adapter.setSelectedPosition(<your desired selected item position>);

adapter.notifyDataSetChanged();
like image 105
Mohd Mufiz Avatar answered Jan 05 '23 17:01

Mohd Mufiz