问题描述
我想在 setAdapter()
方法之后单击某个项目.
I want to perform a click on an item after setAdapter()
method.
考虑一下,如果您已在 Activity 中全局声明并初始化了 Button ,那么您可以在该活动的任何范围内以编程方式对其进行单击,并且侦听器将起作用.我想要类似的东西,以便能够对我的 GridView 中的任何项目进行点击.
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.
到目前为止,我已经一个一个地尝试了以下所有方法,但是它们似乎都不起作用,我尝试了不同的堆栈问题,但是甚至没有一个答案对我有用. iconsGrid.setSelection(2);
, iconsGrid.setSelected(true);
, iconsGrid.performClick();
, iconsGrid.performItemClick(iconsGrid,2,2);
, iconsGrid.performItemClick(iconsGrid,2,iconsGrid.getItemIdAtPosition(2));
,
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;
}
推荐答案
好的,让我们这样做
在适配器中声明一个字段,说
declare one field in your adapter say
private int selectedPosition=-1;
现在为此创建一个setter
now create a setter for this
private void setSelectedPosition(int position)
{
selectedPosition=position;
}
现在在您的getView方法中
Now in your getView method
if(position==selectedPosition)
{
grid.setSelected(true);
//OR
grid.setBackgroundColor(<Some Color>);
}
现在设置适配器后
adapter.setSelectedPosition(<your desired selected item position>);
adapter.notifyDataSetChanged();
这篇关于Android-以编程方式选择GridView的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!