在Android中,onContextItemSelected只有一个MenuItem参数,因此不清楚如何识别所选的视图.MenuItem.getMenuInfo提供对Contextmenu.ContextMenuInfo的访问,但是虽然两个已知子类都提供对目标视图的访问,但接口上似乎没有访问者.
一种替代方法是将View提供的内容保存onCreateContextMenu在私有类变量中,该变量依赖于之前onCreateContextMenu未在活动中再次调用onContextItemSelected.另一种是使用的标识View为itemId的说法ContextMenu.add.如果我们这样做,那么我们需要通过使用其(可能是国际化的)标题来识别从上下文菜单中选择的选项.
识别View所选内容的最佳方法是什么onContextSelected?
对于Android中的选项菜单或上下文菜单,没有"识别所选视图"的概念.因此,回答你的问题相当困难.所以,我会做一些猜测.
如果"标识选择查看"你的意思是哪个菜单项被选中,也就是getItemId()在MenuItem传递给onOptionsItemSelected()或onContextItemSelected().
如果通过"识别所选的视图",则表示a ListView中的哪一行是长按的,以调出上下文菜单,强制转换getMenuInfo()(调用MenuItem)AdapterView.AdapterContextMenuInfo,然后根据适配器使用或者适当id的position值.请参阅此处以获取使用此技术的示例项目.
如果通过"识别所选视图"意味着您ListView在活动中有多个非上下文菜单,我将不会使用该UI技术.
上下文菜单的重点在于它与单个底层视图相关联,并且Android中的设计限制显然是关联在回调'onContextItemSelected'中丢失.在足够大小的任何视图上启用长触摸似乎是完全合理的,可以替代鼠标右键单击.
正如其他帖子所建议的,在某些情况下:
AdapterView.AdapterContextMenuInfo menuInfo =
(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
Run Code Online (Sandbox Code Playgroud)
是合适的,targetView是一个有用的参考点.
另一种方法是子类化视图并覆盖'getContextMenuInfo'以提供视图引用.例如,一个简单的TextView:
package ...;
public class TextViewWithContext extends TextView {
TextViewContextMenuInfo _contextMenuInfo = null;
public TextViewWithContext(Context context) {
super(context);
_contextMenuInfo = new TextViewContextMenuInfo(this);
}
public TextViewWithContext(Context context, AttributeSet attrs) {
super(context, attrs);
_contextMenuInfo = new TextViewContextMenuInfo(this);
}
protected ContextMenuInfo getContextMenuInfo() {
return _contextMenuInfo;
}
public boolean isContextView(ContextMenuInfo menuInfo) {
return menuInfo == (ContextMenuInfo)_contextMenuInfo;
}
protected class TextViewContextMenuInfo implements ContextMenuInfo {
protected TextView _textView = null;
protected TextViewContextMenuInfo(TextView textView) {
_textView = textView;
}
}
}
...
@Override
public boolean onContextItemSelected(MenuItem item) {
ContextMenuInfo menuInfo = item.getMenuInfo();
if (textViewWithContext.isContextView(menuInfo) {
...
}
}
最后,如果基本View类已经为视图指定了一个反向引用的ContextInfo对象,而不是目前的null,那将会更有帮助.
| 归档时间: |
|
| 查看次数: |
9693 次 |
| 最近记录: |