Way to set Home Application Icon in ActionBarSherlock - android

I am confused the way to set home icon on ActionbarSherlock and of course am new to this ActionBarSherlock. Have checked many sources, but unable to get how to set the home icon. Below is my class that sets the ActionbarSherlock.
public abstract class BaseActivity extends SherlockActivity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem miPrefs = menu.add("Login");
miPrefs.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
miPrefs.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
Intent loginIntent = new Intent(BaseActivity.this, LoginForm.class);
startActivity(loginIntent);
return true;
}
});
return true;
}
}
Of course I know how to set application icon as home icon in the normal action bar. The following is the way I usually set the normal actionbar.
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuItem menu1 = menu.add(0, 0, 0, "Login");
menu1.setIcon(R.drawable.image1);
menu1.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}
In the onCreate(), we have to get the actionbar by getActionBar() and then with actionbar.setDisplayHomeAsEnabled(true), it is possible to set the application icon as home icon. By setting the following we can listen to the clicks of home icon.
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case android.R.id.home:
// Here we can keep the code to get to the mainactivity.
return true;
}
}
Also, when I just try to get the actionbar by ActionBar actionbar = getSupportActionBar(); in oncreate(), I get this error,
Type mismatch: cannot convert from com.actionbarsherlock.app.ActionBar to android.app.ActionBar
I'm confused about how to set the application icon as home icon based on the above code of ActionbarSherlock and listen for the clicks. How can I get that done?

Enabling the App Icon to be clickable in the ActionBar (using ABS)
#Override
public void onCreate() {
super.onCreate();
getSupportActionBar().setHomeButtonEnabled(true);
}
ABS is a library so when you want to access it's features, you must use it's own methods/classes, not to be confused with the default Android methods/classes (such as getActionBar() and getSupportActionBar()). A great place for sample code is https://github.com/JakeWharton/ActionBarSherlock/tree/master/samples/demos.
Listening to clicks
The same as what you have above.

Related

Android - toolbar and status bar as shared objects with content changes

In my app I set the toolbar and status bar as shared objects as suggested in option #2 in this post
The general behavior and outline of the toolbar and tabs are excellent - the only issue is that when I move to activity B, some of the UI elements of the Toolbar are not participating in the content transition, particularly the Toolbar title and the menu icons.
I tried adding a SharedElementCallback and in it to loop over the children of the toolbar and tabs and add them all to a Fade transition - but it didn't affect the behaviour of the toolbar and tab content.
Any idea how to proceed from here? The desired effect is to have the elements of the Toolbar (title, up button, menu icons) participate in the content transition.
Added screenshots after comment:
Activity A
Activity B
Each activity has your own menu, so you have to create the menu for each one, even if they are the same.
However, if you prefer, you can create just one menu and create a custom class for manipulate the menu; Then you call this custom class on onCreateOptionsMenu and onOptionsItemSelected from whatever activity.
The following code is an example.
Custom class:
public class MenuActionBar {
public static void createOptionsMenu(final Activity activity, Menu menu) {
activity.getMenuInflater().inflate(R.menu.yourmenu, menu);
// Do whatever you wanna do
}
public static boolean optionsItemSelected(Activity activity, MenuItem item) {
// Do whatever you wanna do
}
}
Activity:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuActionBar.createOptionsMenu(this, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return MenuActionBar.optionsItemSelected(this, item)
? true : 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.

Android - Up navigation in ActionBar on ICS

Up navigation in the Action Bar is simple to setup and works correctly on Jelly Bean:
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
and for that activity in the AndroidManifest
android:parentActivityName=".MainActivity"
but the attribute android:parentActivityName is not available on ICS (4.0.3). The Android documentation is very vague on how to use it on ICS, says
To support older devices with the support library, also include a <meta-data> element that specifies the parent activity as the value for android.support.PARENT_ACTIVITY.
...which I did, but what is this about the support library? I followed the Support Library setup guide on http://developer.android.com/tools/support-library/setup.html but... it still doesn't make the damn up button work in my app on ICS. It's such a small thing, why does it have to be so insanely complicated?
I encountered this problem as well, and wound up with a slightly different solution.
On each screen in my app, I inflate a menu, even if there are no menu options on that screen:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
The code above sets up a menu, but never inflates one.
I then explicitly set the up navigation to point to a specific class. Note the use of android.R.id.home:
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
Intent i = null;
switch (item.getItemId())
{
case android.R.id.home:
i = new Intent(getActivity(), DesiredActivity.class);
startActivityForResult(i, 0);
break;
default:
break;
}
return true;
}
I have tested this on Android version 4.0.3, 4.0.4, 4.4.2 and it works.
You can do what NKijak answered.
Another way to do this is to handle the Up action manually in the Child Activity:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
startActivity(new Intent(this, ParentActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP));
default:
return super.onOptionsItemSelected(item);
}
}
And best part of this manual approach is that it works as expected(resumes the ParentActivity instead of ReCreating it) for all API Levels.
You're extending Activity instead of android.support.v7.app.ActionBarActivity.
Then use getSupportActionBar() instead of getActionBar().

Android: Append not shown ActionItems to Icon instead of Context Menu

I found an example how to use a context menu with actionBar. This example waits for clicks on the phones menu button. But I want to have it appended to the icon or better the activity name. thanks
public class menu extends Activity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_fragen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
..
After the logo and title comes an drop down menu indicator.
That has nothing to do with onCreateOptionsMenu() or onOptionsItemSelected(). To set up that Spinner:
Get your ActionBar via getActionBar()
Call setNavigationMode(ActionBar.NAVIGATION_MODE_LIST) on the ActionBar
Call setListNavigationCallbacks() on the ActionBar with your SpinnerAdapter and a listener object to be notified when the user makes a selection change in the Spinner

Android and ActionBarCompat: how to change visibility of actions at runtime on pre-ICS devices?

I have an Activity that extends ActionBarActivity taken from the ActionBarCompat code sample and I'm trying to show/hide menu items (actions) at runtime.
I've tried using setVisible() on the MenuItem and works for ICS, but in pre-ICS it only change visibility of menu items (menu button press) whereas the ActionBar doesn't get notified of menu changes.
Any solution? Thanks in advance!
I created multiple alternatives of the action bar items under /res/menu/. I keep a member to indicate which one I am using right now. to replace the menu, I call:
protected void setMenuResource(int newMenuResourceId)
{
_menuResource = newMenuResourceId;
invalidateOptionsMenu();
}
And I override onCreateOptionsMenu() to:
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
if (_menuResource != 0)
{
getSupportMenuInflater().inflate(_menuResource, menu);
return true;
}
return super.onCreateOptionsMenu(menu);
}
Now, if I want to change the action Items, I call:
setMenuResource(R.menu.actionbar_menu_X);
This is how i solved it:
In ActionBarHelperBase.java of actionbarcompat project
...
private View addActionItemCompatFromMenuItem(final MenuItem item) {
final int itemId = item.getItemId();
....
The creator of this class copy properties of object, but didn't copy the id of item, so it is impossible to find it later with fiven id.
So i added it in that method:
...
actionButton.setId(itemId);
...
and in the same class i just use:
#Override
public void hideMenuItemById(int id, boolean show){
getActionBarCompat().findViewById(id).setVisibility(show? View.VISIBLE: View.GONE);
}
Hope it helps You.
You have to call supportInvalidateOptionsMenu() which is the relevant method for an ActionBarActivity:
http://developer.android.com/reference/android/support/v7/app/ActionBarActivity.html#supportInvalidateOptionsMenu()

Categories

Resources