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;
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With