我正在学习构建一个用于教育目的的 Android 应用程序,但我遇到了一个问题,想知道是否有人可以提供建议?
我创建了一个网格。第一次初始化时,网格中的每个方 block 都包含占位符图像。当您“长按”网格方 block 时,会出现上下文菜单。然后,用户应该能够选择从图片库上传图像,该图像会调整大小并替换占位符图像,或者他们可以将文本输入到网格方 block 中,创建一个 TextView 对象来替换占位符图像。
我不知道如何确定上下文菜单是从网格中的哪个 View 项打开的。我已经给它们全部添加了标签,但不知道如何访问它,因为 View 对象未传递到 onContextItemSelected 方法。
来 self 的 GridAdapter 的适当代码在这里:
private Integer[] ids = {
android.R.drawable.image, android.R.drawable.image, android.R.drawable.image, android.R.drawable.image, android.R.drawable.image};
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.grid, parent, false);
holder = new Holder();
holder.mView = (View) convertView.findViewById(R.id.grid);
holder.mImageView = (ImageView) convertView.findViewById(R.id.image);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
holder.mImageView.setImageResource(mThumbIds[position]);
return convertView;
}
public static class Holder {
View mView;
ImageView mImageView;
}
}
来 self 的 Grid 类的适当代码:
Gridview gridview = (GridView) findViewById(R.id.gridview);
registerForContextMenu(gridview);
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.uploadmenu, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.group_item1:
//store image in grid square
我有这个方法来修改 GridAdapter 类中的图像,但我不知道如何检索为打开上下文菜单而单击的网格项的位置和资源 ID。
public void updateImage(int position, int resourceId)
{
mThumbIds[position] = resourceId;
notifyDataSetChanged();
}
预先感谢您的任何指导。
最佳答案
在您的onCreateContextMenu
内使用这段代码,
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
position = (int) info.id;
这将为您提供该职位。将其保存为类属性并在 onContextItemSelected
中使用它。
关于java - 如何知道选择 GridView 中的哪个 View 对象来打开上下文菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38694047/