onContextItemSelected called twice for fragment - android

My app has a ListView and I'm using a Contextual Action Bar for devices above SDK 11 and the old popup contextual actions for older devices. I know there's a way to use a CAB with older devices but I tried to implement it and found it wasn't worth the effort for devices that will eventually be obsolete. I know it's some code duplication, but, in theory, I will be getting rid of the old popup actions (emphasis on "in theory").
Anyhow, when I use the emulator, the CAB works fine, but the old popup actions for older devices seems to hit onContextItemSelected twice when I put a breakpoint in that event. I've just start implement a ViewPager for my app and this wasn't happening before the ViewPager so not sure if that is causing the issue.
This is the code I'm using:
public class MyFragment extends SherlockListFragment
{
private ListView mListView;
private android.view.ActionMode mActionMode;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateContextMenu(final ContextMenu menu, final View v, final ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
if (this.mActionMode != null) return;
menu.add(1, 0, 0, "Delete");
menu.add(1, 1, 0, "Save");
}
#Override
public void onActivityCreated(final Bundle icicle)
{
mListView = getListView();
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB)
{
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
mListView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public boolean onCreateActionMode(android.view.ActionMode mode, android.view.Menu menu) {
// Inflate the menu for the CAB
menu.clear();
menu.add(1, 1, 2, "Delete").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add(1, 3, 1, "Save").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return true;
}
#Override
public boolean onActionItemClicked(android.view.ActionMode mode, android.view.MenuItem item) {
mActionMode = mode;
if (item.getGroupId() == 1)
{
switch(itemId)
{
case 0:
DeleteItem();
break;
case 1:
SaveItem();
break;
}
}
}
}
}
}
#Override
public boolean onContextItemSelected(final android.view.MenuItem item) {
if (item.getGroupId() == 1) {
final AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
final Integer position = info.position;
final int itemId = item.getItemId();
switch(itemId)
{
case 0:
DeleteItem();
break;
case 1:
SaveItem();
break;
}
}
return super.onContextItemSelected(item);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu (menu);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.my_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
}
ViewPager code
public class Main extends SherlockFragmentActivity
{
private static List<Integer> mIds;
#Override
public void onCreate(final Bundle icicle)
{
super.onCreate(null);
setContentView(R.layout.main);
mViewPager = (ViewPager)findViewById(R.id.viewpager); //view pager exists, so we are using the portait layout
if (mViewPager != null)
{
mIds = new ArrayList<Integer>();
mIds.add(0);
mIds.add(1);
mIds.add(2);
}
else //in landscape
{
ListFragment lf = (ListFragment)getSupportFragmentManager().findFragmentById(R.id.fragmentList);
if (lf == null)
lf = new ListFragment();
DetailFragment df = (DetailFragment)getSupportFragmentManager().findFragmentById(R.id.fragmentDetail);
if (df == null)
{
df = new DetailFragment();
df.setArguments(getIntent().getExtras());
}
getSupportFragmentManager().beginTransaction().add(R.id.fragmentList, lf).commit();
getSupportFragmentManager().beginTransaction().add(R.id.fragmentDetail, df).commit();
}
}
private static class MyFragmentPagerAdapter extends FragmentStatePagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
//can't use getSupportFragmentManager().findFragmentById() here because I get a "Cannot make a static reference to the non-static method" error
if (index == 0)
return ListFragment.newInstance();
else
return DetailFragment.newInstance(mIds.get(index-1));
}
#Override
public int getCount() {
return 4;
}
}
}

This solution on this question fixed my issue:
How to handle onContextItemSelected in a multi fragment activity?
using getUserVisibleHint() in onContextItemSelected.

Method must return true to consume the selection.
Docs here
#Override
public boolean onContextItemSelected(final android.view.MenuItem item) {
if (item.getGroupId() == 1) {
final AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
final Integer position = info.position;
final int itemId = item.getItemId();
switch(itemId)
{
case 0:
DeleteItem();
return true;
case 1:
SaveItem();
return true;
}
}
return super.onContextItemSelected(item);
}

Related

Fragment-specific options and context menus in Android

How do I realize options and context menus in a "clean" and proper way, when an Activity switches between several fragments?
Here example code using a NavigationDrawer:
public class MainActivity extends Activity implements OnFragmentInteractionListener {
...
#Override
public void onNavigationDrawerItemSelected(int position) {
FragmentManager fragmentManager = getFragmentManager();
switch (position) {
case 0:
fragmentManager.beginTransaction().replace(R.id.container, Fragment1.newInstance(null, null)).commit();
break;
case 1:
fragmentManager.beginTransaction().replace(R.id.container, Fragment2.newInstance(null, null)).commit();
break;
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// ???
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
// ???
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
// ???
return super.onOptionsItemSelected(item);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
//???
super.onCreateContextMenu(menu, v, menuInfo);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
// ???
return super.onContextItemSelected(item);
}
#Override
public void onFragmentInteraction(String id) {
// ???
}
}
public class Fragment1 extends Fragment {
// ???
// option menu item A
// listView1 context menu item X
}
public class Fragment2 extends Fragment {
// ???
// option menu item B
// listView 2 context menu item Y
}
Maybe I am on the wrong track. I am a bit confused...
I understand you want to have different menus for each fragment? You can specify a menu for each fragment and it will only show when that fragment is attached to the Activity. The code below all belongs in a fragment.
You must tell the fragment it has an options menu:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
Then inflate the the menu for this fragment:
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.about, menu);
}
Then handle each item in the menu when it is clicked:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle menu item click here
return super.onOptionsItemSelected(item);
}
You can also specify a "global" menu in the activity and those menu item will be shown as well as the menu items for the current fragment.

contextual action mode in fragment - close if not focused?

i implemented a contextual action mode bar in a nested fragement. This fragment is part of a view pager and the view pager is also a fragment and part of a navigation drawer.
My Problem: I want to close the contextual action mode bar if the fragment is no more focused. So, if I swipe through the view pager the action mode bar should close. But if I use the onPause() method of the nested fragment, the method is not called directly. Often it waits until i swiped two or three times forward... Here are some pictures:
In the second picture you can see that the action mode bar is still there. So my question is:
In which method should I call my actionModeBar.finish() method, to close directly the action mode bar if i leave the fragment?
Maybe the code of the fragment helps you:
public class EditorFragment extends Fragment {
private static final String KEY_POSITION="position";
ListView listView;
private boolean isMultipleList = false;
private ActionMode acMode;
private int counterChecked = 0;
private ActionMode.Callback modeCallBack = new ActionMode.Callback() {
public boolean onPrepareActionMode(ActionMode mode, Menu menu){
return false;
}
public void onDestroyActionMode(ActionMode mode) {
listView.clearChoices();
for (int i = 0; i < listView.getChildCount(); i++)
listView.setItemChecked(i, false);
listView.post(new Runnable() {
#Override
public void run() {
listView.setChoiceMode(ListView.CHOICE_MODE_NONE);
}
});
isMultipleList = false;
counterChecked = 0;
mode = null;
}
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.setTitle("1 Aufgabe");
mode.getMenuInflater().inflate(R.menu.actionmode, menu);
return true;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.actionmode_delete:
int choiceCount = listView.getCount();
SparseBooleanArray spBoolArray = listView.getCheckedItemPositions();
DBAufgaben db = new DBAufgaben(MainActivity.getMContext());
db.open();
for (int i = 0; i < choiceCount; i++) {
if(spBoolArray.get(i)){
db.deletContact(listView.getItemIdAtPosition(i));
}
}
Cursor cursor = db.getAllRecords();
AdapterEingang adapterE = new AdapterEingang(MainActivity.getMContext(), cursor, 0);
listView.setAdapter(adapterE);
db.close();
mode.finish();
break;
case R.id.actionmode_cancel:
mode.finish();
break;
}
return false;
}
};
//......//
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = null;
int position = getArguments().getInt(KEY_POSITION, -1);
switch(position){
case 0:
rootView = inflater.inflate(R.layout.pager_list, null);
listView = (ListView) rootView.findViewById(R.id.pager_list);
Context context = MainActivity.getMContext();
DBAufgaben db = new DBAufgaben(context);
db.open();
Cursor cursor = db.getAllRecords();
AdapterEingang adapterE = new AdapterEingang(context, cursor, 0);
listView.setAdapter(adapterE);
db.close();
listView.setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view,
int position, long id) {
if(!isMultipleList){
acMode = MainActivity.getInstance().startActionMode(modeCallBack);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setItemChecked(position, true);
isMultipleList = true;
counterChecked++;
setNewTitle();
} else {
listView.setItemChecked(position, true);
counterChecked++;
setNewTitle();
}
return true;
}
});
listView.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position,
long id) {
Log.d(getTag(), "Datensatz: "+String.valueOf(id));
if(isMultipleList){
if(listView.isItemChecked(position)){
listView.setItemChecked(position, true);
counterChecked++;
setNewTitle();
} else {
listView.setItemChecked(position, false);
counterChecked--;
setNewTitle();
}
}
}
});
break;
default:
rootView = inflater.inflate(R.layout.frag_dummy, null);
TextView txt = (TextView) rootView.findViewById(R.id.dummy_txt);
txt.setText(String.valueOf(position));
break;
}
return(rootView);
}
public void setNewTitle(){
if(counterChecked == 1){
acMode.setTitle(counterChecked+" Aufgabe");
} else {
acMode.setTitle(counterChecked+" Aufgaben");
}
}
#Override
public void onPause(){
super.onPause();
if(isMultipleList){
acMode.finish();
}
}
}
ViewPagers keep multiple pages active at any one time (by default, the page before and page after the currently shown page), hence why onPause() is not called until you swipe two pages away.
Your best bet would be to use a ViewPager.OnPageChangeListener, and show and hide the ActionMode in onPageSelected(..) (i.e. if the page selected isn't the one with the ActionMode, hide the ActionMode). You'll likely have to implement this in the Activity which hosts your ViewPager.
Here's what worked for me --
Hold a static reference to the action mode in MyFragment:
public static ActionMode mActionMode;
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mActionMode = mode;
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
Set ViewPager.OnPageChangeListener in MyViewPagerActivity.
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
....
#Override
public void onPageScrollStateChanged(int state) {
if(MyFragment.mActionMode != null) MyFragment.mActionMode.finish();
}
});
This worked for me:
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
if (!isVisibleToUser && this.listView != null) {
//HACK this is done in order to finish the contextual action bar
int choiceMode = this.listView.getChoiceMode();
this.listView.setChoiceMode(choiceMode);
}
}
I combined code from the OP with the override suggested by user pomber:
I save the ActionMode to a class field when the action mode is created.
I set the field back to null when the action mode is destroyed.
I override setUserVisibleHint in my fragment and call ActionMode#finish() if the fragment isn't visible in the view pager.
I also call ActionMode#finish() in the onPause() method of the fragment to close the fragment if the user navigates elsewhere.
Code:
#Nullable
ActionMode mActionMode = null;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Start out with a progress indicator.
setListShownNoAnimation(false);
setEmptyText(getText(R.string.no_forms_in_progress));
getListView().setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
// Here you can do something when items are selected/de-selected,
// such as update the title in the CAB
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context_saved_item, menu);
inflater.inflate(R.menu.context_instance_list, menu);
mActionMode = mode;
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.action_delete:
confirmDelete(getListView().getCheckedItemIds());
return true;
case R.id.action_print:
print(getListView().getCheckedItemIds());
return true;
}
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
});
}
#Override
public void onPause() {
super.onPause();
if (mActionMode != null) {
mActionMode.finish();
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (mActionMode != null && !isVisibleToUser) {
mActionMode.finish();
}
}
You can use the onDestroyOptionsMenu() method inside your Fragment:
public void onDestroyOptionsMenu() {
super.onDestroyOptionsMenu();
if (mActionMode != null) {
mActionMode.finish();
mActionMode = null;
}
}

SlidingMenu lib and ActionBarSherlock with uiOptions = splitActionBarWhenNarrow

everyone!
I'm using SlidingMenu library with ActionBarSherlock. When I setup uiOptions to splitActionBarWhenNarrow, ActionItems from bottombar are not clicable. This problem is reproduced only on android v2.3 and less. I think that SlidingMenu intercepts touch on ActionItem in the bottombar. If I touch on ActionItem and slide SlidingMenu, ActionItem becomes selected. I try to add actionItem as ignored to SlidingMenu, but it doesn't help:(
This is example of my code:
public class ExampleFragment extends BaseFragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_positions, null);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
((BaseActivity)getActivity()).getSlidingMenu().clearIgnoredViews();
final SubMenu deal = menu.addSubMenu(R.string.deal).setIcon(R.drawable.ic_actionbar_deal);
deal.add(1, R.string.close_position, 0, R.string.close_position);
deal.add(1, R.string.open_position, 0, R.string.open_position);
final MenuItem dealItem = deal.getItem();
dealItem.setIcon(R.drawable.ic_actionbar_deal);
dealItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
final SubMenu edit = menu.addSubMenu(R.string.change).setIcon(R.drawable.ic_actionbar_edit);
edit.add(2, R.string.change_limitation, 0, R.string.change_limitation);
final MenuItem editItem = edit.getItem();
editItem.setIcon(R.drawable.ic_actionbar_edit);
editItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
if(DataContext.getInstance().getOpenPositions().size() == 0){
menu.findItem(R.string.close_position).setEnabled(false);
menu.findItem(R.string.change_limitation).setEnabled(false);
}
menu.add(0, R.string.reports, 0, R.string.reports).setIcon(R.drawable.ic_actionbar_report_stub).
setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
ignoreMenuItems(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.string.open_position:
Log.v(TAG, "onOptionsItemSelected open_position");
break;
case R.string.close_position:
Log.v(TAG, "onOptionsItemSelected close_position");
break;
case R.string.change_limitation:
Log.v(TAG, "onOptionsItemSelected change_limitation");
break;
case R.string.reports:
Log.v(TAG, "onOptionsItemSelected reports");
break;
}
return true;
}
public void ignoreMenuItems(Menu menu){
for(int i = 0; i < menu.size(); i++){
final MenuItem item = menu.getItem(i);
View view = getActivity().getLayoutInflater().inflate(R.layout.layout_action_view, null);
((ImageView) view.findViewById(R.id.action_view_image)).setImageDrawable(item.getIcon());
if(item.getSubMenu() != null){
item.getSubMenu().setHeaderView(view);
} else {
item.setActionView(view);
view.setLongClickable(true);
view.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
onOptionsItemSelected(item);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
Toast.makeText(getActivity(), item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
});
}
((BaseActivity)getActivity()).getSlidingMenu().addIgnoredView(view);
}
}
Any ideas?

Using Contextual action bar with fragments

I am currently working on android project and making use of fragments and ListViews/ListFragments. I have contextual action bars working on standard activities such as a ListActivity.
Now I am trying to do the same sort of thing but on a fragment layout. I have a MainActivity which extends Activity which inflates the XML for the layout that contains the 2 fragments, fragment A and fragment B.
Fragment A extends ListFragment and contains a ListView which is populated from data within an SQLite Database. When I have got a contextual action bar working on a standard ListActivity I have a class that Extends ListView.MultiChoiceModeListener but this isn't available for a ListFragment class or a standard activity so how would I go about implementing this.
The basic thing I want to achieve is when someone long presses the item within a ListView within FragmentA which extends ListFragment, the action bar contextually changes and the user can then select multiple items from within the ListView.
Thanks for any help you can provide.
When I have got a contextual action bar working on a standard
ListActivity I have a class that Extends
ListView.MultiChoiceModeListener but this isn't available for a
ListFragment class or a standard activity so how would I go about
implementing this.
I don't see how MultiChoiceModeListener isn't available (maybe I didn't understand what you try to do). From your comment I assumed you use the fragments from the compatibility package.
Below is an example with a FragmentActivity with two static fragments and each of those fragments triggers the contextual action bar with their own menus options.
The FragmentActivity is very simple, it just holds the two fragments below:
// the list fragment
public class ListCABFragment extends ListFragment {
private String[] mCountries = { "Romania", "Germany", "England", "USA",
"Japan", "France" };
private static final boolean POST_HONEYCOMB = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (POST_HONEYCOMB) {
// make sure we are on a version above Honeycomb otherwise will
// access things that aren't available
postHoneycombCAB();
} else {
// probably do nothing and implement the normal context menu?!?
}
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, mCountries));
}
#SuppressLint({ "NewApi", "NewApi" })
private void postHoneycombCAB() {
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
((ListView) parent).setItemChecked(position,
((ListView) parent).isItemChecked(position));
return false;
}
});
getListView().setMultiChoiceModeListener(new MultiChoiceModeListener() {
private int nr = 0;
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
getActivity().getMenuInflater().inflate(R.menu.listcab_menu,
menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.item1:
Toast.makeText(getActivity(), "Option1 clicked",
Toast.LENGTH_SHORT).show();
break;
case R.id.item2:
Toast.makeText(getActivity(), "Option2 clicked",
Toast.LENGTH_SHORT).show();
break;
}
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
nr = 0;
}
#Override
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked) {
if (checked) {
nr++;
} else {
nr--;
}
mode.setTitle(nr + " rows selected!");
}
});
}
}
and the other fragment for a Fragment which has a layout composed from a RadioGroup which triggers the CAB when a RadioButton is selected:
public class SimpleCABFragment extends Fragment implements Callback {
private static final boolean POST_HONEYCOMB = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.frag_simplecabfragment, container,
false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
RadioGroup rg = (RadioGroup) getView().findViewById(R.id.radioGroup1);
rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (POST_HONEYCOMB) {
// this could be improved so we don't need to create the
// option
// menu if it is already available
getActivity().startActionMode(SimpleCABFragment.this);
} else {
// something else
}
}
});
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
if (item.getItemId() == R.id.itemradio) {
Toast.makeText(getActivity(), "CAB for Radiogroup!",
Toast.LENGTH_SHORT).show();
}
return false;
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
getActivity().getMenuInflater().inflate(R.menu.simplecab_menu, menu);
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
}
See if this is what you're looking for (you can find a full sample including the layouts and menus files in my github project).

Android Activity Group - second activity always shows first activity menu

I have one problem using ActivityGroup. I have two activities inside an ActivityGroup and both of them use a menu (overriding the onCreateOptionMenu and onOptionsItemSelected).
Both activity have different menus.
Well, the problem is that the second activity always show the first activity menu,
Any idea about this issue?
Below is my code
public class myActivityGroup extends ActivityGroup {
----
public void startChildActivity(String Id, Intent intent) {
Window window = getLocalActivityManager().startActivity(Id, intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
if (window != null) {
mIdList.add(Id);
View view = window.getDecorView();
history.add(view);
setContentView(view);
}
}
public void back() {
if (history.size() > 0) {
int lastActivityIndex = history.size() - 1;
int lastIDIndex = mIdList.size() - 1;
String activityId = mIdList.get(lastIDIndex);
Log.d(TAG, "activityId:" + activityId);
history.remove(lastActivityIndex);
mIdList.remove(lastIDIndex);
setContentView(history.get(history.size() - 1));
} else {
finish();
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
Activity current = getLocalActivityManager().getCurrentActivity();
return current.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
LocalActivityManager manager = getLocalActivityManager();
Activity current = manager.getCurrentActivity();
return current.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
LocalActivityManager manager = getLocalActivityManager();
Activity current = manager.getCurrentActivity();
return current.onOptionsItemSelected(item);
}
}
public class ChildActivity1 extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//add menu here
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.settings_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//handle on menu item selected here
return true;
}
}
public class ChildActivity2 extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//add menu here
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.offer_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//handle on menu item selected here
return true;
}
}
When you add the activities, the "current" activity is that last one added. I suspect that if you interact with the other activity then activate the options menu it will work.
Try retrieving the activity you need using the String Id:
LocalActivityManager manager = getLocalActivityManager();
Activity a = manager.getActivity(id);
return a.onCreateOptionsMenu(menu);

Categories

Resources