I am not getting how to show only selected action items on some activities. Below is my code:
public abstract class BaseActivity extends SherlockActivity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add("Login")
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add("Save")
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case 0:
Intent loginIntent = new Intent(BaseActivity.this,LoginForm.class);
startActivity(loginIntent);
return true;
case 1:
Intent saveIntent = new Intent(BaseActivity.this,SaveForm.class);
startActivity(saveIntent);
return true;
}
return false;
}
}
In the above code I am setting action items so that I can reuse this action items in some activities without repeating the code. Whenever I want these action items to be displayed on particular activity, I am extending this BaseActivity on the present activity as below.
public class FirstActivity extends BaseActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
....
....
}
So, whenever I need these action items on the particular activities, I am extending the baseactivity to the activities on which I need. Now my problem is how to set only selected action items on particular activity. Suppose I don't want to show up "login" action Item on one activity. How can I get this done? Code snippets would be appreciated.
Now it's a reasonable approach but I would only have items that were reused for all in the baseactivity. That said I think the correct way of handling this would be to override the methods with the implementation you want in these other activities.
You could have some variables that is set in onCreate(), if these are true/false handle it accordingly in onCreateOptionsMenu()
Edit
To override in your own activity you simply do the same thing as in the baseactivity but without calling initializing those buttons you don't need.
If you instead want to make toggle if buttons should be there or not simply add the variables to your baseactivity:
protected boolean mIsLoginButton = true;
Change the onCreateOptionsMenu() method in baseactivity to something like this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if(mIsLoginButton) {
menu.add("Login")
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}
menu.add("Save")
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return true;
}
Then in your firstActivity you simply do this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mIsLoginButton = false;
}
Related
I am displaying overflow menu list when we click the three dots. When I press home button and again when I launch the app, overflow menu list is still displaying. How to dismiss overflow menu list window?
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.v("RAMKUMARV ONCREATEOPTION", "RAMKUMARV");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem item = menu.findItem(R.id.action_settings);
item.setVisible(true);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You can have an activity field that stores the options/overflow menu whenever the onCreateOptionsMenu() gets triggered, and then use close() method to dismiss the menu when the home button is clicked i.e. in onUserLeaveHint().
public class MainActivity extends AppCompatActivity {
// Field to store the overflow menu
private Menu mOverflowMenu;
// omitted rest of your code
#Override
public boolean onCreateOptionsMenu(Menu menu) {
mOverflowMenu = menu;
// omitted rest of your code
return true;
}
// Dismissing the overflow menu on home button click
#Override
protected void onUserLeaveHint() {
super.onUserLeaveHint();
mOverflowMenu.close();
}
}
Declare the menu item like at MainActivity level, like this:
public class MainActivity extends AppCompatActivity {
private MenuItem overflowItem;
...
}
Now you should instanciate the object inside the onCreateOptionsMenu method, like this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
...
overflowItem = menu.findItem(R.id.action_settings);
overflowItem.setVisible(true);
return true;
}
Then you can use the onPause method to set the overflowItem not visible anymore:
#Override
public void onPause() {
super.onPause();
overflowItem.setVisible(false);
}
Finally remember to replace your MenuItem item object with overflowItem where it is used.
To dismiss the overflow menu you can simply call closeOptionsMenu() inside Activity.
closeOptionsMenu()
Progammatically closes the options menu. If the options menu is
already closed, this method does nothing.
You can call it in onPause() method like below:
#Override
public void onPause() {
super.onPause();
closeOptionsMenu();
}
or in case you want to call it only when the user presses the Home key you can use onUserLeaveHint() like below:
#Override
protected void onUserLeaveHint() {
super.onUserLeaveHint();
closeOptionsMenu();
}
I have an ActionBar activity with a FrameLayout and a menu. when the user clicks the menu item I replace the fragment with the relevant new fragment. However, I cannot see an obvious way to remove the menu item for the selected fragment.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
StudyFragment startFragment = new StudyFragment();
startFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add
(R.id.container, startFragment).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_study:
replaceFragment((Fragment)new StudyFragment());
break;
case R.id.action_list:
replaceFragment((Fragment)new ListFragment());
break;
// etc
}
return super.onOptionsItemSelected(item);
}
private void replaceFragment(Fragment f) {
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, f);
transaction.addToBackStack(null);
transaction.commit();
}
The Google documentation on changing menus says to disable the menu in onPrepareOptionsMenu - but how will I know which item has been selected?
--Solution Implemented--
Using Muhammed Refaat's solution below I added two new members to the class:
private Menu activityMenu;
private MenuItem curMenuItem;
Set them in onCreateOptionsMenu
activityMenu = menu;
curMenuItem = activityMenu.findItem(R.id.action_study);
curMenuItem.setVisible(false);
And changed them on onOptionsItemSelected
curMenuItem.setVisible(true);
curMenuItem = activityMenu.findItem(id);
curMenuItem.setVisible(false);
First get the item you want to remove :
MenuItem item = menu.findItem(R.id.your_action);
then set it's Visibility false :
item.setVisible(false);
and if the problem is in getting the menu (as it's not in the fragment), you can easily get a context from the activity that contains the menu and get the menu by it.
Inside your fragment you will have to use setHasOptionsMenu(true); in order to access options menu from within your fragment.
Code (inside your second fragment where you wanna hide the item):
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO your code to hide item here
super.onCreateOptionsMenu(menu, inflater);
}
Similarly, for your fragment where you want to show that MenuItem you can do the similar thing.
In the fragment where you want to hide the Item
#Override
public void onPrepareOptionsMenu(Menu menu) {
MenuItem item=menu.findItem(R.id.action_search);
item.setVisible(false);
and in onCreate() of your fragment
setHasOptionsMenu(true);
Adding to Muhammed's answer above. Once the item has been set as invisible, you may need to also disable the item. Note Google's comment: "Even if a menu item is not visible, it may still be invoked via its shortcut (to completely disable an item, set it to invisible and disabled)" under setVisible() in the MenuItem documentation.
Thus:
item.setVisible(false);
item.setEnabled (false);
Add below codes into your fragment
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem item = menu.findItem(R.id.save);
item.setVisible(false);
}
// create Boolean variable in the main activity
private var menuvisibile: Boolean = true
// while navigating fragments set the menuvisibile value and use it
// variable as part of the return statement
invalidateOptionsMenu()
menuvisibile = false
override fun onCreateOptionsMenu(menu: Menu?): Boolean
{
val menuInflater = menuInflater
menuInflater.inflate(R.menu.notification,menu)
return menuvisibile
}
working well for me.
I have two fragment activities and one fragment. Here's how the app logic looks like:
FragmentActivity A ==> Fragment B ==> FragmentActivity C.
FragmentActivity A is the parent activity of fragment B and has an options menu that shows correctly.Fragment B contains a listview. When a list item is clicked on fragment B,its details are displayed in FragmentActivity C.Now i want to display an options menu inside C in the actionBar.However, the menu is only displayed after the menu button is clicked.I want it as an actionbar action.
Here is the code for Activity C:
public class LatestDetailsFragment extends FragmentActivity implements
OnItemClickListener {
public LatestDetailsFragment() {
photoImages = new ImageItem();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_latestdetails);
gallery.setOnItemClickListener(this);
// setHasOptionsMenu(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.details_fragment_menu, menu);
return super.onCreateOptionsMenu(menu);
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.contact:
ContactOwnerFragment contactFragment = new ContactOwnerFragment();
Bundle bundle = new Bundle();
bundle.putString(KEY_PHONE, phone);
contactFragment.setArguments(bundle);
contactFragment.show(getSupportFragmentManager(), "contact");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
And the menu:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="be.hcpl.android.example.MainActivity" >
<item
android:id="#+id/contact"
android:icon="#drawable/ic_action_call"
android:orderInCategory="100"
android:title="#string/contact"
app:showAsAction="ifRoom|withText">
</item>
I cannot use setHasOptionsMenu(true); on the activity because it raises an error,I don't know why. I want to display an icon on the actionbar.
You need to use menu.clear() before inflating menus.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.clear();
getMenuInflater().inflate(R.menu.details_fragment_menu, menu);
return super.onCreateOptionsMenu(menu);
}
From the Documents
public abstract void clear () Remove all existing items from the menu, leaving it empty as if it had just been created.
I aim to shared the action bar in all activities. So I create a based class call "MyActionBarActivity" as follows"
public class MyActionBarActivity extends ActionBarActivity {
public final static int TL = Toast.LENGTH_LONG;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Toast.makeText(getApplicationContext(), "I am settings", TL).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
and other activities inherit from this class to share the action bar.
public class Activity1 extends MyActionBarActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_1);
}}
public class Activity2 extends MyActionBarActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
}}
Is this a good way to implement the action bar?
In my opinion this is a fine way to apply the common action bars in more than one activity.
But inflating in separate activities also won't make much difference.
You can use either ways.
I have an activity for my menu events:
public class GlobalMenu extends Activity{
private MenuItem item;
public boolean event(MenuItem item){
this.item = item;
// Handle item selection
switch (this.item.getItemId()) {
case R.id.menu_stop:
finish();
return true;
}
return true;
}
}
And I use it like this
GlobalMenu gm = new GlobalMenu();
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return gm.event(item);
}
But the finish didn't work, I think I need to link it with an application but I don't know how to do
Thanks
First of All, You can't make a Object or Instance of Android Activity.
like this
GlobalMenu gm = new GlobalMenu();
You have to pass a Context of GlobalMenu Activity to other Activity or Class and then call finish on this.
Like,
((GlobalMenu)mContext).finish();
Here mContext is a reference of GlobalMenu Activity.