Android - actionBar.setDisplayHomeAsUpEnabled issues - android

In my activity which extends SherlockFragmentActivity I have action bar and have also set actionBar.setDisplayHomeAsUpEnabled(true) to come back to my previous activity. Everything works fine. But when i click on home button, the background color should be applied only to the app icon but it also applies to the "title" on action bar as shown in screen shot. I dont want this to happen. When i click on home button, only the app icon should be click able(background color should be applied only for app icon) and not the title. Any idea how can i do this?
my activity code:
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(some_string);

Don't forget this part, because that home button is also a MENU button.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This is called when the Home (Up) button is pressed in the action bar.
// Create a simple intent that starts the hierarchical parent activity and
// use NavUtils in the Support Package to ensure proper handling of Up.
Intent upIntent = new Intent(this, MainActivity.class);
if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
// This activity is not part of the application's task, so create a new task
// with a synthesized back stack.
TaskStackBuilder.from(this)
// If there are ancestor activities, they should be added here.
.addNextIntent(upIntent)
.startActivities();
finish();
} else {
// This activity is part of the application's task, so simply
// navigate up to the hierarchical parent activity.
NavUtils.navigateUpTo(this, upIntent);
}
return true;
}
return super.onOptionsItemSelected(item);
}

The standard Android UI pattern is to include the title in the pressed state.
However, I think if you followed this link (describing how to add a custom view to the left of an actionbar) How to align items in action bar to the left? , and set the title to empty. The below code worked on my local device
ActionBar action=getActionBar();
action.setDisplayShowCustomEnabled(true);
action.setHomeButtonEnabled(true);
action.setDisplayShowTitleEnabled(false);
TextView title =new TextView(getApplicationContext());
title.setText("Your Title here");
title.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
action.setCustomView(title);

Related

returning back to main activity from SettingActivity

I got SettingActivity from AndroidStudio Gallery, which uses ActionBar. Everything is fine when I click back button from ActionBar inside SettingsActivity. But when I want to return to main activity using this button in ActionBar nothing happens.
My SettingsActivity uses headers for preferences, so I thought I can check whether I am "inside" any of these headers, and if answer is none then I am in main setting screen and I can call main activity using startActivity(this,MainActivity.class). But problem is I cann't determine whether I am in start screen or in some header. Of course if there are more easy ways to do it I would appreciate it very much.
to make action bar back press return back , you have to do it in menu item selected
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
Intent homeIntent = new Intent(this, HomeActivity.class);
homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
}
return (super.onOptionsItemSelected(menuItem));
}

Android Toolbar with both home and back button

Is it possible to display both home icon and back icon in the toolbar?
1) Is it possible change the order of display of back button icon and home icon.
Currently it displays the arrow button first and then the logo (home button)
2) Second requirement is to clear the activity stack on clicking the home icon and going back to previous screen in case of back button.
I have the following code which will display a arrow back key and home icon which is set as logo. Is it possible to handle click events on both these icons:
Toolbar toolbar = (Toolbar)findByViewID(R.id.toolbar);
toolbar.setNavigationIcon(R.drwable.btn_back);
setSuppportActionBar(toolbar);
getSupportActionBar().setLogo(R.drawable.home_icon);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
I am able to handle to the click on arrow icon by handling it in onOptionsITemSelected method.
Is there a way to handle click on logo icon?
My idea is to use the home button click to clear the stack of activities and use the back button to navigate back to previous screen.
I tried with
toolbar.setNavigationOnClickListener()
but it has no effect on back button click.
Handling android.R.id.home works when handled in
onOptionsItemSelected()
For navigating back. This worked for me.
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
Intent homeIntent = new Intent(this, HomeActivity.class);
homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
}
return (super.onOptionsItemSelected(menuItem));
}
try with this
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
getActivity().finish();
}
return true;
}
});
Design our custom layout as a separate "toolbar_content.xml" and include this layout inside toolbar tag in your "main_layout.xml".
Write click listeners for your items in "toolbar_content.xml" in your base activity so that listeners will be available thru out the app.

How can I programmatically set a parent activity in android [duplicate]

So at the moment I have an activity that can be reached from two different activities, the problem is that I can only set one activity as the parent activity in the manifest XML file. Obviously this is bad UX/UI design because the activity may send the user back to the wrong activity they were at previously and so I'm trying to dynamically set which activity is the parent activity.
The trouble is I'm not quite sure how to go about this, whether in code or XML so any pointers are appreciated. :)
For future readers here's an example of how to actually implement the official/proper solution as per the developer guides (scroll to the paragraph beginning with "This is appropriate when the parent activity may be different...").
Note that this solution assumes you are using the Support Library to implement your ActionBar and that you can at least set a 'default' parent Activity in your manifest XML file to fallback on if the Activity you are backing out of is in a 'task' that doesn't belong to your app (read the linked docs for clarification).
// Override BOTH getSupportParentActivityIntent() AND getParentActivityIntent() because
// if your device is running on API 11+ it will call the native
// getParentActivityIntent() method instead of the support version.
// The docs do **NOT** make this part clear and it is important!
#Override
public Intent getSupportParentActivityIntent() {
return getParentActivityIntentImpl();
}
#Override
public Intent getParentActivityIntent() {
return getParentActivityIntentImpl();
}
private Intent getParentActivityIntentImpl() {
Intent i = null;
// Here you need to do some logic to determine from which Activity you came.
// example: you could pass a variable through your Intent extras and check that.
if (parentIsActivityA) {
i = new Intent(this, ActivityA.class);
// set any flags or extras that you need.
// If you are reusing the previous Activity (i.e. bringing it to the top
// without re-creating a new instance) set these flags:
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
// if you are re-using the parent Activity you may not need to set any extras
i.putExtra("someExtra", "whateverYouNeed");
} else {
i = new Intent(this, ActivityB.class);
// same comments as above
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
i.putExtra("someExtra", "whateverYouNeed");
}
return i;
}
NOTE: If you do not set a default parent Activity in the manifest XML file then you'll also need to implement onCreateSupportNavigateUpTaskStack() since the system will have no idea how to generate a backstack for your task. I have not provided any example for this part.
My thoughts on the finish() type solutions
On my searching for a solution to this problem I came across a few answers that advocate the strategy of overriding onOptionsItemSelected() and intercepting the android.R.id.home button so they could simply finish() the current Activity to return to the previous screen.
In many cases this will achieve the desired behavior, but I just want to point out that this is definitely not the same as a proper UP navigation. If you were navigating to the child Activity through one of the parent Activities, then yes finish() will return you to the proper previous screen, but what if you entered the child Activity through a notification? In that case finish()ing by hitting the UP button would drop you right back onto the home screen or whatever app you were viewing before you hit the notification, when instead it should have sent you to a proper parent Activity within your app.
Like this way you can navigate dynamically to your parent activity:
getActionBar().setDisplayHomeAsUpEnabled(true);
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
NOTE: It redirects you to the activity or fragment where you came from, no matter whether it's a parent or not. Clicking on the action bar Up/Home button will just finish the current activity.
There are two concepts in play here 'Up' and 'Back'. 'Back' is the obvious one: take me to where I was just before I came here. Usually you don't need to be concerned with 'Back', as the system will handle it just fine. 'Up' is not so obvious - it's analogous to Zoom Out - from an element to the collection, from a detail to the wider picture.
Which of these fits your use case?
As per comment below: the up button pulls the destination from the android manifest, but it can be customized programmatically.
The method to override is getParentActivityIntent.
Here is my code and works perfectly fine.
#Override
public Intent getParentActivityIntent() {
Intent parentIntent= getIntent();
String className = parentIntent.getStringExtra("ParentClassSource");
Intent newIntent=null;
try {
//you need to define the class with package name
newIntent = new Intent(OnMap.this, Class.forName(className));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return newIntent;
}
From the parent activities;
Intent i = new Intent(DataDetailsItem.this, OnMap.class);
i.putExtra("ParentClassSource", "com.package.example.YourParentActivity");
startActivity(i);
To find out how to use Up Navigation properly see this Android Dev Guide.
Note that there is a big flaw in the above Android Dev Guide as the NavUtils functions work differently for ICS(and lower) and JellyBean(and higher). This flaw in NavUtils is explained beautifully here.
Generally, a 'detail' type of activity will have to provide the 'up' navigation if it has nested/related contents. The 'back' navigation is handled by the system so you really don't have to worry about it.
Now for the extra effort to support the 'up' navigation, there are a few ways of doing it:
Activity that has the parent activity defined in the AndroidManifest.
Your Android Manifest
---------------------
<activity
android:name="com.example.app.DetailActivity"
android:parentActivityName="com.example.app.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.app.MainActivity" />
</activity>
Your Detail Activity
--------------------
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
This works well if there's only one parent activity meaning if the (DetailActivity) always gets launched from (MainActivity). Otherwise this solution will not work if (DetailActivity) gets launched from different places.
More here: http://developer.android.com/training/implementing-navigation/ancestral.html
(Easier and Recommended) Activity with Fragment and Fragment back-stack:
Your Detail Activity
--------------------
protected void replaceFragment(Bundle fragmentArguments, boolean addToBackStack) {
DetailFragment fragment = new DetailFragment();
fragment.setArguments(fragmentArguments);
// get your fragment manager, native/support
FragmentTransaction tr = fragmentManager.beginTransaction();
tr.replace(containerResId, fragment);
if (addToBackStack) {
tr.addToBackStack(null);
}
tr.commit();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
In this solution, if the user presses 'back', the fragment will be popped from the fragment backstack and the user is taken back to the previous fragment while still remaining in the same activity. If the user presses the 'up', the activity dismisses and the user is lead back to the previous activity (being the parent activity). The key here is to use the Fragment as your UI and the activity as the host of the fragment.
Hope this helps.
You can override the Up button to act like the back button as following:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
You will need to keep track of the parent activity. One way to do this is by storing it as an extra in the intent you create to start the child activity). For example, if Activity A starts Activity B, store A's intent in the intent created for B. Then in B's onOptionsItemSelected where you handle the up navigation, retrieve A's intent and start it with the desired intent flags.
The following post has a more complex use-case with a chain of child activites. It explains how you can navigate up to the same or new instance of the parent and finish the intermediate activities while doing so.
Android up navigation for an Activity with multiple parents
Kotlin 2020
My activity launches from different activities so the AndroidManifest only works with 1 parent activity.
You can return to the previous activity like this:
supportActionBar?.setDisplayHomeAsUpEnabled(true)
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when(item!!.itemId){
android.R.id.home -> {
finish()
return true
}
}
return super.onOptionsItemSelected(item)
}

Actionbar set the home button

I am using a NavigationDrawer with my ActionBar. It needs the home button and configured as up.
I try to put a button in the middle of the action. The only way I found is to use a custom layout.
But when I use it, my home title is erased. Even if it has the space to be displayed.
Is there a way to set the home button to always show his title ?
If not is there an other trick ?
Thanks in advance :)
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setHomeButtonEnabled(true);
and add
// For back Button
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
Intent homeIntent = new Intent(this, DashbordActivity.class);
homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
}
return (super.onOptionsItemSelected(menuItem));
}
try following code
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setHomeButtonEnabled(true);

Android - Click on ActionBar app icon, create new activity instance

I have an ActionBar in my Android app (API Level 14).
There is a home button with my app icon. In MainActivity I write a short Text in an EditText View.
When I navigate to PreferenceActivity the icon gets an arrow to signal me, I can navigate to home Activity (MainActivity).
// PreferenceActivity-onCreate
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
I click on that app icon in ActionBar to return to MainActivity
// PreferenceActivity
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Now my MainActivity was created again und the text in EditText is gone.
I thought I can keep alive the MainActivity with die Intent.FLAG_ACTIVITY_CLEAR_TOP.
I want to have a behaviour like i use my return button on device.
If you want to return to an existing instance of MainActivity, you need to do this:
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
Using CLEAR_TOP alone causes a new instance of MainActivity to be created.
I believe this is the correct way of doing this. https://stackoverflow.com/a/15933890/238768
Using Intent.FLAG_ACTIVITY_CLEAR_TOP will cause the exact opposite behaviour of what Gepro wants to do!

Categories

Resources