我想在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;
}
答案 0 :(得分:7)
好的,让我们这样做
声明适配器中的一个字段说
private int selectedPosition=-1;
现在为此
创建一个setterprivate 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();
答案 1 :(得分:3)
在GridView内的xml文件中添加android:listSelector="@drawable/your_selector"
添加此行后,如果你编码像 -
gridView.setSelection(POSITION); //position starts from 0
它将突出显示该特定项目。
并执行点击使用 -
gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
//do whatever you want to do
}
});