我有GridView
:
GridView gridView = (GridView) findViewById(R.id.grid_view);
// Instance of ImageAdapter Class
final String [] imageNames = {"knee_kg","knee_ks","knee_kp","knee_kg_90",
"pipe_knee", "cover", "funnel", "crater"};
Integer[] mThumbIds = new Integer[imageNames.length];
for (int i = 0; i<imageNames.length; i++){
Integer resID = getResources().getIdentifier(imageNames[i], "drawable",
getPackageName());
mThumbIds[i] = resID;
}
和OnItemCliclListener
:
gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
Class clazz = null;
String className = imageNameToUpper(imageNames[position]);
try {
clazz = Class.forName("com.example.pipecalculator.activities." + className);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent intentClass = new Intent(getApplicationContext(), clazz);
startActivity(intentClass);
}
});
我只想在单击两个项目时创建上下文菜单:"knee_ks"
、"knee_kp"
。另一方面是:
Intent intentClass = new Intent(getApplicationContext(), clazz);
startActivity(intentClass);
有可能?
这是可能的。
您应该使用int position
:
gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
if (position == 0 || position == 2 /*and other, or just: position < 5*/)
{
//Code for positio 0 and 2
}
else
{
//Code for othe positions
}
}
});
使用此示例显示上下文菜单。
首先注册网格视图以获取上下文菜单
registerForContextMenu(grid);
,然后覆盖函数
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.context_menu, menu);
GridView gv = (GridView) v;
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
int position = info.position;
if(!(position==0 || position==2))
{
menu.close();
)
}
上下文菜单侦听器
@Override
public boolean onContextItemSelected(MenuItem item) {
return true;
}
这似乎是一个古老的话题,但我遇到了同样的问题,想放弃对我有用的东西。基于@Abhishek命题,我所做的只是用menu.clear()
代替menu.close()
语句,瞧!上下文仅出现在位置 0 和 2 上。
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.context_menu, menu);
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
int position = info.position;
if(!(position==0 || position==2)){
menu.clear();
}
}