Call an Activity by using Click on SideBar Navigation Menu Item - android

How to Call an Activity while using Side Navigation in Android.
I am using this sample :Navigation menu for Android (based off Google+ app)
https://github.com/darvds/RibbonMenu
Here i want, whenever user will click on Home then need to call CategoryActivity and when do click on Home2 then need to call OptionsActivity and so on.....
RibbonsampleActivity.Java:
public class RibbonsampleActivity extends Activity implements iRibbonMenuCallback {
/** Called when the activity is first created. */
private RibbonMenuView rbmView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rbmView = (RibbonMenuView) findViewById(R.id.ribbonMenuView1);
rbmView.setMenuClickCallback(this);
rbmView.setMenuItems(R.menu.ribbon_menu);
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
rbmView.toggleMenu();
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
#Override
public void RibbonMenuItemClick(int itemId) {
// Handle item selection
}
}
ribbon_menu.xml:
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/ribbon_menu_home" android:title="Home" android:icon="#drawable/ic_launcher"></item>
<item android:id="#+id/ribbon_menu_home2" android:title="Home2" android:icon="#drawable/ic_launcher"></item>
<item android:id="#+id/ribbon_menu_home3" android:title="Home3" android:icon="#drawable/ic_launcher"></item>
I want to call activities by using particular Side Bar Navigation Item:
Home > CategroyActivity
Home2 > OptionsActivity
Home3 > ArrowActivity

you have got a null pointer in getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar() returns null. there could be couple of reasons for this, most probably this could be an issue of your project setup. check your AndroidManifest.xml and remove if you have set a "fullscreen" or "no title bar" theme.

I was facing the same issue. Solution for this problem is you need to use Fragment instead of Activity.
Best Example here: http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/

Related

Remove Toolbar items on runtime

I have a Toolbar within my app which I would like to modify it contents dynamically, during the app execution (in other words, on run-time).
For example, the app is capable of taking and previewing photos; once that photos are previewed, the user is able to select some photos and perform a sending action to a server. I want also to make the user able to delete photos once that some of them are selected and for doing that I would like that the "delete" item on the action bar (identifiable via the trash icon) will be visible only when one or more photos are selected.
Is this possible to do?
If yes, how?
In other words and, more generically, I want to control items (visibility) in the toolbar, setting the code as they will be "visible" only when some conditions are "true" (in the example above, when photos are selected or, in a different example, when user is logged) and invisible when they are "false" (when user isn't logged).
For now I just need to "remove" (or make invisible) items in the Toolbar, but it will be useful also to know if is possible to add items in the toolbar on run-time.
I'm adding some code which can help to understand the problem.
app_bar.xml file in "/res/layout", which graphically defines the Toolbar
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:elevation="4dp"
android:theme="#style/ToolbarTheme" />
menu_resources.xml file, which defines the Toolbar items
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- "User favourite function", should appear as action button if possible -->
<item
android:id="#+id/action_app_icon"
android:icon="#mipmap/ic_launcher"
android:title="#string/action_bar_app_icon"
app:showAsAction="always" />
<!-- Settings, should always be in the overflow -->
<item
android:id="#+id/action_delete"
android:icon="#drawable/trash"
android:title="#string/action_bar_delete"
app:showAsAction="always"/>
<!-- Settings, should always be in the overflow -->
<item
android:id="#+id/action_settings"
android:icon="#drawable/settings"
android:title="#string/action_bar_settings"
app:showAsAction="never"/>
<!-- About, should always be in the overflow -->
<item
android:id="#+id/about"
android:icon="#android:drawable/ic_dialog_info"
app:showAsAction="never"
android:title="#string/action_bar_about"/>
Part of the activity in which the toolbar is
public class myClass extends AppCompatActivity implements View.OnClickListener {
// Instantiating a toolbar
private Toolbar toolbar;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_class);
// Adding toolbar to the activity
toolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
// Get a support ActionBar corresponding to this toolbar
ActionBar ab = getSupportActionBar();
// Enable the Up button
ab.setDisplayHomeAsUpEnabled(true);
}
// The method that creates an options menu
#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_resource, menu);
// This make the delete item invisible
menu.findItem(R.id.action_delete).setVisible(false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
// Perform the settings action
return true;
case R.id.about:
// Perform the about
return true;
case R.id.action_delete:
deletePhotos();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public static void manageSelection(Boolean state, int position){
if (photoArray.getNumberSelected() == 0) {
// disable the trash icon and its functionality;
} else {
// enable the trash icon with its functionality;
}
}
// This method allows to deleteItems images to the array
public void deletePhotos() {
//code for deleting photos
}
}
Thanks for your time.
Try this code in your activity please:
public class ActivityClass extends AppCompatActivity {
MenuItem menuItem; // Make global toolbar's menuItem
.
.
.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_layout, menu);
menuItem = menu.findItem(R.id.toolbar_action_button) // Your toolbar´s button ID and save it in your global menuItem
return super.onCreateOptionsMenu(menu);
}
public void showMenuItem(){
menuItem.setVisible(true); // Call this method in runtime when you need show it
}
public void hideMenuItem(){
menuItem.setVisible(false); // Call this method in runtime when you need hide it
}
[EDIT]
Thanks to Alessandro Iudicone´s comment we have an alternative way to get the toolbar´s menu too without the global MenuItem but only global Toolbar instance:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_layout, menu);
return super.onCreateOptionsMenu(menu);
}
public void showMenuItem(){
toolbar.getMenu().findItem(R.id.toolbar_actio‌​n_button).setVisible‌​(true);
}
public void hideMenuItem(){
toolbar.getMenu().findItem(R.id.toolbar_actio‌​n_button).setVisible‌​(false);
}
Hope it helps :)
For hiding the icon:
toolbar.findViewById(R.id.menu_item_id).setVisibility(View.INVISIBLE);
For adding a view to the toolbar:
TextView textView = new TextView(MainActivity.this);
textView.setText("Hello World");
toolbar.addView(textView);
This only works for views on the toolbar itself, not for the overflow menu. You'll probably have to use code found in this stack overflow answer if you want to mess with the overflow menu: Android Toolbar overflow menu view id

Get the ID of a MenuItem in a toolbar

I have a "menu" resource "menu_test" with the following code:
<?xml version="1.0" encoding="utf-8"?>
<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=".TestActivity" >
<item android:id="#+id/hideshow"
android:title="Body visbility"
android:orderInCategory="100"
android:icon="#drawable/showicon"
app:showAsAction="always" />
</menu>
In my activity.java I inflate the toolbar in the "onCreate" function and add a click listener:
private Toolbar toolbar;
...
toolbar = (Toolbar)findViewById(R.id.toolbarId);
toolbar.inflateMenu(R.menu.menu_test);
toolbar.setOnMenuItemClickListener(this);
I would like to get the ID of "hideshow" and change the icon:
testItem = (MenuItem) toolbar.findViewById(R.id.hideshow);
testItem.setIcon(R.drawable.hideicon);
However to app crashes when getting the ID in the first line. In the click listener function it works fine, since the ID is provided internally with the click:
public boolean onMenuItemClick(MenuItem item)
item.setIcon(R.drawable.hideicon);
So how can I change the icon within the onCreate function? ("findItem" does not work, since toolbar is not a menu)
I may be easier to add the menu items programmatically so you can maintain a reference to them:
public class MainActivity extends AppCompatActivity {
private static final int MENU_SETTINGS = Menu.FIRST;
MenuItem menuItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menuItem = menu.add(0, MENU_SETTINGS, 0, R.string.action_settings).setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_SETTINGS:
// DO SOMETHING
break;
}
return super.onOptionsItemSelected(item);
}
}
As the other answers and comments indicate, one needs a reference from onCreateOptionsMenu or onPrepareOptionsMenu.
In my case, this would require a lot of code rewrite, as this is an old project, where everything is based on using toolbars instead of menus.
However, I found an easy solution:
Instead of finding the ID and changing the icon, I created several instances of menu_test[1 .. n].xml with different icons and simply use inflateMenu(R.menu.menu_test[1 .. n]) depending on the icon I need.
If you write new code, use the solution from Abtin Gramian, so I mark that as the proper answer.

PreferenceFragment not shown on clicking settings menu option

I am trying to display custom preferences on clicking Settings options in the app. I have a listview in my MainActivity. On clicking settings, there is some INCOMPLETE VIEW displayed on top of MainActivity. And on clicking this view, the PreferenceFragment is visible with the settings layout. The listview scrolling gets disabled as a result of this view added on top of MainActivity.java. I need to display the PreferenceFragment as soon as Settings menu is clicked, instead of this incomplete view.
Please find my code below
MainActivity.java
MainActivity extends FragmentActivity{
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();
}
}
}
PreferenceFragment.java
public class SettingsFragment extends PreferenceFragment{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
Any help is welcome !!
You can look that post to know how to create Preference Activity :
https://stackoverflow.com/a/23545532/5652770

How to know whether navigation back is clicked?

I have added a PreferenceScreen in my application that include back navigation. When I click the navigation icon, it doesn't save what I make in PreferenceScreen. So, how can I handle navigation back click.
You can simply override the onBackPressed...
#Override
public void onBackPressed()
{
// code here to save the change
super.onBackPressed(); // optional depending on your needs
}
As PreferenceActivity is a subclass of Activity, it should follow the same lifecycle. Click on the link and then navigate to Indirect Subclasses or here is the direct http://developer.android.com/reference/android/preference/PreferenceActivity.html
Edits
In your case you are using the as parent activity to MainActivity, that's why it is getting re-created when you press the navigation back. remove the line from manifest.
<activity
android:name=".UserSettingActivity"
android:label="#string/app_name"
(remove this line) android:parentActivityName=".MainActivity" >
</activity>
and change the code of your settings Activity as ..
public class UserSettingActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.user_settings);
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case android.R.id.home:
Log.e("onOptionsItemSelected", "home");
finish();
return false;
}
return super.onOptionsItemSelected(item);
}

How to create optionmenu for android 3.0 and higher version and option menu icon not showing in higher version mobiles

How to create optionmenu for Android 3.0 and higher version mobiles?
I am trying to create options menu in my Android program. I am using the following code to inflate options menu. option menu icon not showing in higher version mobiles..
public class MainScreenTab extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "Merchants", "Personal Payee" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_screen_tab_layout);
//Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu); //inflate our menu
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.
// switch(item.getItemId()) {
int id = item.getItemId();
if (id == R.id.item_refresh) {
Intent i = new Intent(MainScreenTab.this,ListMerchantType.class);
startActivity(i);
return true;
}
else if (id == R.id.item_save) {
Intent i = new Intent(MainScreenTab.this,ListPayee.class);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
}
You just need to use this Reflection method to force your icon in the ActionBar
public static void forceOverFlowIconInActionBar(Activity mActivity)
{
try
{
ViewConfiguration config = ViewConfiguration.get(mActivity);
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if(menuKeyField != null)
{
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
Try this one. import java.lang.reflect.Field; And on your onCreateOptionsMenu() method just simply add:
if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
try {
Field field = menu.getClass().getDeclaredField("mOptionalIconsVisible");
field.setAccessible(true);
field.setBoolean(menu, true);
} catch (Exception ignored) {
ignored.printStackTrace();
}
}
and don't forget to add this to your xml menu android:icon="#drawable/blah_blah" . Hope it helps. And don't forget to up-vote if it is helpful.
Menus: Generally a list of commands or facilities displayed on screen. It is a common user interface for the user. If you want to provide a familiar and consistent user experience you should use Menus in your activity. It is beginning with android 3.0(Api level 11). So design and user experience my change for device to device that is depends on the Menu apis.
There mainly there menus in the android. Those are Options menu, Context menu, Popup Menu.
Options menu:
Options menu is a collection of menu items for an activity. The place where you locate icons that is very impact to the app. Such menu items are search, settings, compose email.
If you are developing the options menu for Android 2.3 and lower user can reveal the options menu by pressing menu button. On the 3.0 and higher the options menu items as a combination of action bar items. Beginning with Android 3.0, the Menu button is deprecated (some devices don't have one), so you should migrate toward using the action bar to provide access to actions and other options.
Creating Options Menu in android
Simply options menu is where you should you include options and other actions what are relevant to activity. The item in the options menu is depends on the version you are using.
If it is below 3.0 that comes when you press the menu buttons. If it is higher that will comes to the top of the screen. Means that will include with the action bar screen.
You can declare items for the options menu from either your Activity subclass or a Fragment subclass. At one time if you declare both the items in the activity then that will appear one followed another. You can also reorder the menu items in the android:orderInCategory attribute in each you need to move.
To specify a menu item in the activity first you need to override one method. That method is onCreateOptionsMenu() . This mehtod fragments provide their own onCreateOptionsMenu() callback.
Example:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.game_menu, menu);
return true;
}
We can perform add and retrieve options in the menu item api by using add() and findItem().
Handling click events in onCreateOptionsMenu():
If you want to provide a click event on the menu items the system calls onOptionsItemSelected. In that method you can identify which item you are selected by using item.getItemId(). which returns the unique ID for the menu item (defined by the android:id attribute in the menu resource or with an integer given to the add() method). You it is matched you can perform your action whatever you want.
Example:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.new_game:
newGame();
return true;
case R.id.help:
showHelp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
When you successfully handle the menu item that will returns true. If not handle that item that will you should call the superclass implementation of onOptionsItemSelected().
Changing menu items at runtime:
When you call onCreateOptionsMenu() that is displaying simple onCreateOptionsMenu(). you can not change the items in the run time. If you want to change the items in the run time you need to call onPrepareOptionsMenu() method. This method passes you the Menu object as it currently exists so you can modify it, such as add, remove, or disable items.
Example Project:
Open your eclipse and create one project name called OptionsMenu.
In that open you menu folder in the resource folder. In the main.xml file add how many items you want. You can get main.xml file below.
Main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="#+id/menu_settings" android:orderInCategory="100"
android:showAsAction="never" android:title="#string/menu_settings"/>
<item android:id="#+id/item1" android:title="Tutorial 1"></item>
<item android:id="#+id/item2" android:title="Tutorial 2"></item>
<item android:id="#+id/item3" android:title="Tutorial 3"></item>
<item android:id="#+id/item4" android:title="Tutorial 4"></item>
<item android:id="#+id/item5" android:title="Tutorial 5"></item>
</menu>
Here i used #string/menu_settings so you can add that item in the strings.xml file.
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">OptionsMenu</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
</resources>
Once that is done open your main activity. In that write the onCreateOptionsMenu method for adding the menu item to the activity. Once that is done if you want to give click events you write onOptionsItemSelected. You can get the complete code below.
MainActivity
package com.tutorialindustry.optionsmenu;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item1:
Toast.makeText(this, "Tutorial 1 Selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.item2:
Toast.makeText(this, "Tutorial 2 Selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.item3:
Toast.makeText(this, "Tutorial 3 Selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.item4:
Toast.makeText(this, "Tutorial 4 Selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.item5:
Toast.makeText(this, "Tutorial 5 Selected", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Once that is done run you project that you can get the below output. In this way we can perform options menu in the android.

Categories

Resources