我想在setAdapter()
方法后对项目执行单击。
考虑一下,如果您已经在活动中全局声明并初始化了一个按钮,那么您可以从该活动的任何范围以编程方式对其执行单击,监听器将工作。我想要类似的东西,能够在我的gridview的任何项目上执行一次点击。
到目前为止,我已经一个接一个地尝试了下面所有的方法,但似乎没有一个有效,我尝试了不同的堆栈问题,但甚至没有一个答案对我有效。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;
}
最佳答案
好吧,我们这样做吧
在适配器中声明一个字段
private int selectedPosition=-1;
现在为这个创建一个setter
private void setSelectedPosition(int position)
{
selectedPosition=position;
}
现在在getview方法中
if(position==selectedPosition)
{
grid.setSelected(true);
//OR
grid.setBackgroundColor(<Some Color>);
}
现在在设置适配器之后
adapter.setSelectedPosition(<your desired selected item position>);
adapter.notifyDataSetChanged();