How can I override the button display home - java

By default the button(setDisplayHomeAsUpEnabled), returns the parent activity, how would I change it? For example: I need to back to a Intent
toolbar = (Toolbar) findViewById(R.id.tb_dados);
toolbar.setTitle("Adicione uma descrição");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

You can try this....
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
// your intent code here.
break;
}
return super.onOptionsItemSelected(item);
}

you can use onOptionsItemSelected method and perform any other function if you want
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
Toast.makeText(this, "back Button Clicked", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}

Since you are using custom toolbar so you can easily use custom toolbar like this
toolbar.setNavigationIcon(R.drawable.back_arrow);// use your back arrow image
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(this,MainActivity.class));//call which activity you want in back press
finish();
}
});

Related

Add event when back arrow(getSupportActionBar().setDisplayHomeAsUpEnabled(true)) is clicked

My problem is almost the same as this Stop AsyncTask in Fragments when Back Button is pressed
But I want to stop my AsyncTask when the back arrow is clicked. I have a code in stoping asynctask and it works when I implemented it in another way. I tried what I researched so far but I still got errors. Please help me with this.
I tried this code
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
if(id==android.R.id.home)
{
Intent returnIntent = new Intent();
returnIntent.putExtra("flag",userid);
setResult(Activity.RESULT_OK,returnIntent);
finish();
return true;
}}
UPDATED:
I am using this code to go to another fragment.
Fragment2 fragmentChild = new Fragment2 ();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.content, fragmentChild);
transaction.addToBackStack(null);
transaction.commit();
I have no problem in my backtrack when I go to another fragment. Then I'm using this code (getSupportActionBar().setDisplayHomeAsUpEnabled(true)) in my (Drawer.java) to show the back arrow. Now I want to add event when I clicked back arrow.
EDIT: (Drawer.java)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
final View.OnClickListener originalToolbarListener = toggle.getToolbarNavigationClickListener();
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
toggle.setDrawerIndicatorEnabled(false);
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getSupportFragmentManager().popBackStack();
}
});
} else {
toggle.setDrawerIndicatorEnabled(true);
toggle.setToolbarNavigationClickListener(originalToolbarListener);
}
}
});
If you properly setup the action bar, then you should be able to achive that with the following:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// Add the code to stop the task
break;
}
return super.onOptionsItemSelected(item);
}
EDIT: After you are able to handle the back button event, you can add the code to close the tasks in fragments. First of all, I created an interface that is implement by all fragments that should be able to close this tasks.
public interface TaskCancelFragment {
void cancelTask();
}
The implementation in fragments should look something like this:
#Override
public void cancelTask() {
//Add the code to cancel the task
Toast.makeText(getContext(), "The task is canceled", Toast.LENGTH_SHORT).show();
}
The final step is to send the event from activity to fragment. Here I will assume some things since I don't have access to your code to see how you add/find the fragments, but fortunately this doesn't matter so much and is easy to change. In addition to the initial answer, I created a new method in activity to find the current fragment and close the task.
private void cancelTasks() {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.placeholder);
if (fragment instanceof TaskCancelFragment) {
((TaskCancelFragment) fragment).cancelTask();
}
}
And in the end, the case android.R.id.home looks like this:
case android.R.id.home:
cancelTasks();
onBackPressed(); // I think that you want to close the activity too
break;

How to display and set click event on Back Arrow on Toolbar?

How can I set back arrow in Android toolbar and also apply click listener?
First make one toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="#color/colorPrimary"
local:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
local:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
then include it in activity_main.xml like this way:
<LinearLayout
android:id="#+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
</LinearLayout>
then in your MainActivity.java file, put this code:
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("MyTitle");
To add listener on back press, use following method:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// todo: goto back activity from here
Intent intent = new Intent(CurrentActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Toolbar mToolbar= (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// perform whatever you want on back arrow click
}
});
// with lamda expression
toolbar.setNavigationOnClickListener(view -> onBackPressed());
If you are using the default back button for android by using
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Then override the onOptionsItemSelected like
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//do whatever
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Complete example here http://www.freakyjolly.com/how-to-add-back-arrow-in-android-activity/
Use getSupportActionBar() Activity on which you want to show Back Icon
In OtherActivity.class
public class OtherActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.other_activity);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
}
This will add a event listen
If you want to know when home is clicked is an AppCompatActivity then you should try it like this:
Use this code :
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Listen for click events on android.R.id.home like usual:
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == android.R.id.home) {
Intent intent = new Intent(CurrentActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
return super.onOptionsItemSelected(menuItem);
}
Add this
Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
and in onOptionsItemSelected add this
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Check this
Display Back Arrow on Toolbar Android
http://developer.android.com/intl/es/training/implementing-navigation/ancestral.html
Very simple code. Add inside onCreateView() method of activity
To display icon
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
and to add click listener
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Put your click logic here
}
});

Android Up button not working

I am trying to manually implement the actions that must take place when the up button on the actionbar is pressed but for some reason nothing happens when I press it.
here is my code:
public class ActivityOne extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_one);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar_actionbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Button button = (Button)findViewById(R.id.btn1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivityTwo();
}
});
Button button2 = (Button)findViewById(R.id.btn2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivityThree();
}
});
}
void openActivityTwo(){
Intent intent = new Intent(this, ActivityTwo.class);
startActivity(intent);
}
void openActivityThree(){
Intent intent = new Intent(this, ActivityThree.class);
startActivity(intent);
}
#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_activity_one, 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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
else if(id == R.id.homeAsUp){
Log.i("","Up is pressed");
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
I understand that I have to explicitly assign a parent activity for the activity I want to implement up navigation on the manifest file, but problem is that this activity has multiple parents so I thought calling the finish() method when the up button is pressed on this activity will be the better approach.
I have already tried both id == R.id.home and id == R.id.homeAsUp and they both do not work. I do not know if it is because I am using AppCompactActivity or what Please help
Here is how you can implement this, try this code
use android.R.id.home instead of R.id.home or R.id.homeAsUp
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//use onBackPressed() OR finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
The correct way to do it is to override public boolean onNavigateUp() just like overriding onBackPressed().
Using android studio 3.6.2 I've found that the Up button is not displayed by default in my apps, but it can be easily added..
Go to AndroidManifest.xml and update each activity that needs an Up button as follows:
<activity
android:name=".yourClassName"
android:parentActivityName=".MainActivity">
<meta-data android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.yourPackageName" />
</activity>
The target destination for the Up button is set by changing parentActivityName. In this example I have set it as '.MainActivity' but you can change that to whatever activity you want the user to navigate to.

Implementing Up navigation on fragment

I have a MainActivity which contains FragmentA. When I click on FragmentA, this happens:
getFragmentManager().beginTransaction().replace(R.id.container,new PrefFragment()).addToBackStack("back").commit();
I have this in my manifest:
<activity>
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MainActivity" />
</activity>
and this in MainActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_head_sound);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new FragmentA)
.commit();
}
getActionBar().setDisplayHomeAsUpEnabled(true);
}
But the Up Button navigation is always visible.
FragmentB contains this code:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
switch (id)
{
case android.R.id.home:
getFragmentManager().popBackStack();
Toast.makeText(getActivity(),"CLick",Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
This code doesn't run.
I need to implement Up navigation only in FragmentB. How can I do that?
As far as I understand the up navigation must work only in FragmentB, whereas if FragmentA is shown the up navigation will be hidden. If so, then in Activity, remove getActionBar().setDisplayHomeAsUpEnabled(true); from onCreate.
Also you must return true when you handled menu click, and move the onOptionsItemSelected(MenuItem) to Activity since android.R.id.home menu click is only delivered to the Activity.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getFragmentManager().popBackStack();
Toast.makeText(getActivity(),"CLick",Toast.LENGTH_SHORT).show();
return true; //Notice you must returning true here
default:
return super.onOptionsItemSelected(item);
}
}
In FragmentA
#Override
public void onAttach(Activity a) {
super.onAttach(a);
a.getActionBar().setDisplayHomeAsUpEnabled(false);
}
In FragmentB
#Override
public void onAttach(Activity a) {
super.onAttach(a);
a.getActionBar().setDisplayHomeAsUpEnabled(true);
}

How do I start an Activity with the HomeButton of the ActionBar

At the moment i use this code:
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB){
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
, but now the Button shouldnt be only a back-function. I like to start an other activity:
Intent intent = new Intent(CurrentActivity.this, MainActivity.class);
startActivity(intent);
I know i should use the setOnClickListener, but I don't know where i call the Listener.
Although I agree with Tanis.7x comment, you shouldn't be using that button if it's not to go back by calling finish() or popBackStack(),
the action for the home button is called with the menu options
http://developer.android.com/guide/topics/ui/actionbar.html#Home
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked;
return true;
default:
return super.onOptionsItemSelected(item);
}
}

Categories