我的活动包含两个片段,与同一个班级相关联。
使用上下文菜单,当我从第二个片段/列表视图中选择菜单操作时,记录实例成员会显示仅从第一个片段实例调用onContextItemSelected:
public class LikedFragment extends Fragment {
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMyInstanceId = getArguments().getString("fragmentId"); // "first" or "second"
}
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.my_fragment, container, false);
mAdapter = new MyAdapter(mActivity, MyQueries.getMyCursor(mMyInstanceId));
AbsListView listView = (AbsListView) mView.findViewById(android.R.id.list);
listView.setAdapter(mAdapter);
listView.setOnCreateContextMenuListener(this);
return mView;
}
@Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getActivity().getMenuInflater().inflate(R.menu.menu_item_liked, menu);
Log.d(TAG, mMyInstanceId); // OKAY: logs "second"
}
@Override public boolean onContextItemSelected(MenuItem item) {
Log.d(TAG, mMyInstanceId); // FAIL: logs "first"
/* ... */
}
}
如何在onContextItemSelected中获得正确的实例?
答案 0 :(得分:0)
只需使用组ID来解决此问题。只需为片段和片段分配不同的组ID即可。然后在onContextItemSelected中检查它们,如下所示。
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo)
{
menu.add(GROUP_ID, MENU_1, 0, "Menu 1");
menu.add(GROUP_ID, MENU_2, 0, "Menu 2");
}
public boolean onContextItemSelected(MenuItem item)
{
//only this fragment's context menus have group ID of -1
if (item.getGroupId() == GROUP_ID)
{
//Your Code Will Be Added Here
}