Display back button on action bar

試著忘記壹切 提交于 2019-11-26 03:48:02

问题


I\'m trying to display a Back button on the Action bar to move previous page/activity or to the main page (first opening). And I can not do it.

my code.

ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);

the code is in onCreate.


回答1:


well this is simple one to show back button

actionBar.setDisplayHomeAsUpEnabled(true);

and then you can custom the back event at onOptionsItemSelected

case android.R.id.home:
this.finish();
return true;



回答2:


I think onSupportNavigateUp() is the best and Easiest way to do so, check the below steps. Step 1 is necessary, step two have alternative.

Step 1 showing back button: Add this line in onCreate() method to show back button.

assert getSupportActionBar() != null;   //null check
getSupportActionBar().setDisplayHomeAsUpEnabled(true);   //show back button

Step 2 implementation of back click: Override this method

@Override
public boolean onSupportNavigateUp(){  
    finish();  
    return true;  
}

thats it you are done
OR Step 2 Alternative: You can add meta to the activity in manifest file as

<meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="MainActivity" />

Edit: If you are not using AppCompat Activity then do not use support word, you can use

getActionBar().setDisplayHomeAsUpEnabled(true); // In `OnCreate();`

// And override this method
@Override 
public boolean onNavigateUp(){ 
     finish(); 
     return true; 
}

Thanks to @atariguy for comment.




回答3:


The magic happens in onOptionsItemSelected.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            // app icon in action bar clicked; go home
            Intent intent = new Intent(this, HomeActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}



回答4:


Official solution

Add those two code snippets to your SubActivity

@Override
public void onCreate(Bundle savedInstanceState) {
    ...
    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:
        NavUtils.navigateUpFromSameTask(this);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

add meta-data and parentActivity to manifest to support lower sdk.

 <application ... >
    ...
    <!-- The main/home activity (it has no parent activity) -->
    <activity
        android:name="com.example.myfirstapp.MainActivity" ...>
        ...
    </activity>
    <!-- A child of the main activity -->
    <activity
        android:name="com.example.myfirstapp.SubActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.myfirstapp.MainActivity" >
        <!-- Parent activity meta-data to support 4.0 and lower -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity" />
    </activity>
</application>

Reference here:http://developer.android.com/training/implementing-navigation/ancestral.html




回答5:


Add these lines to onCreate()

android.support.v7.app.ActionBar actionBar = getSupportActionBar();
   actionBar.setHomeButtonEnabled(true);
   actionBar.setDisplayHomeAsUpEnabled(true);

and in onOptionItemSelected

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                //Write your logic here
                this.finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

Hope this will help you..!




回答6:


Try this code, considers it only if you need the back button.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //YOUR CODE
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    //YOUR CODE
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    onBackPressed();
    return true;
}



回答7:


On your onCreate method add:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

While defining in the AndroidManifest.xml the parent activity (the activity that will be called once the back button in the action bar is pressed):

In your <activity> definition on the Manifest, add the line:

android:parentActivityName="com.example.activities.MyParentActivity"



回答8:


I know I'm a bit late, but was able to fix this issue by following the docs directly.

Add the meta-data tag to AndroidManifest.xml (so the system knows)

 <activity
        android:name=".Sub"
        android:label="Sub-Activity"
        android:parentActivityName=".MainChooser"
        android:theme="@style/AppTheme.NoActionBar">
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value=".MainChooser" />
    </activity>

Next, enable the back (up) button in your MainActivity

    @Override 
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_child);

    // my_child_toolbar is defined in the layout file 
    Toolbar myChildToolbar =
        (Toolbar) findViewById(R.id.my_child_toolbar);
    setSupportActionBar(myChildToolbar);

    // Get a support ActionBar corresponding to this toolbar 
    ActionBar ab = getSupportActionBar();

    // Enable the Up button 
    ab.setDisplayHomeAsUpEnabled(true);
    } 

And, you will be all set up!

Source: Android Developer Documentation




回答9:


I know that the above are many helpful solutions, but this time I read this article (current Android Studio 2.1.2 with sdk 23) some method above doesn't work.

Below is my solution for sub-activity is MapsActivity

First, you need to add parentActivity in

AndroidManifest.xml

like this :

<application ... >
    ...
    <!-- Main activity (which has no parent activity) -->
    <activity
        android:name="com.example.myapp.MainActivity" ...>
        ...
    </activity>
    <!-- A child of the main activity -->
    <activity
        .....
        android:parentActivityName=".MainActivity" >
        <!-- Support Parent activity for Android 4.0 and lower -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myapp.MainActivity" />
    </activity>
</application>

Second, ensure that your sub-Activity extends AppCompatActivity, not FragmentActivity.

Third, override onOptionsItemSelected() method

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // app icon action bar is clicked; go to parent activity
                this.finish();
                return true;
            case R.id.action_settings:
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

Hope this will help!




回答10:


Try this, In your onCreate()

 getActionBar().setHomeButtonEnabled(true);
 getActionBar().setDisplayHomeAsUpEnabled(true);

And for clickevent,

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // app icon in action bar clicked; goto parent activity.
                this.finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }



回答11:


To achieve this, there are simply two steps,

Step 1: Go to AndroidManifest.xml and add this parameter in the <activity> tag - android:parentActivityName=".home.HomeActivity"

Example:

<activity
    android:name=".home.ActivityDetail"
    android:parentActivityName=".home.HomeActivity"
    android:screenOrientation="portrait" />

Step 2: In ActivityDetail add your action for previous page/activity

Example:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
    }
    return super.onOptionsItemSelected(item);
}



回答12:


This is simple and works for me very well

add this inside onCreate() method

getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

add this outside oncreate() method

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    onBackPressed();
    return true;
}



回答13:


in onCreate method write-

Toolbar toolbar = findViewById(R.id.tool);
    setSupportActionBar(toolbar);
    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }
}
@Override
public boolean onSupportNavigateUp() {
    onBackPressed();
    return true;
}
@Override
public void onBackPressed() {
    super.onBackPressed();
    startActivity(new Intent(ActivityOne.this, ActivityTwo.class));
    finish();
}

and this is the xml file-

<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark"
android:id="@+id/tool">

and in styles.xml change it to

Theme.AppCompat.Light.NoActionBar

this is all what we have to do.




回答14:


I Solved in this way

@Override
public boolean  onOptionsItemSelected(MenuItem item){
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

@Override
public void onBackPressed(){
    Intent backMainTest = new Intent(this,MainTest.class);
    startActivity(backMainTest);
    finish();
}



回答15:


my working code to go back screen.

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

    case android.R.id.home:

        Toast.makeText(getApplicationContext(), "Home Clicked",
                Toast.LENGTH_LONG).show();

        // go to previous activity
        onBackPressed();

        return true;

    }

    return super.onOptionsItemSelected(item);
}



回答16:


 public void initToolbar(){
       //this set back button 
       getSupportActionBar().setDisplayHomeAsUpEnabled(true);
       //this is set custom image to back button
       getSupportActionBar().setHomeAsUpIndicator(R.drawable.back_btn_image);
}


//this method call when you press back button
@Override
public boolean onSupportNavigateUp(){
    finish();
    return true;
}



回答17:


ActionBar actionBar=getActionBar();

actionBar.setDisplayHomeAsUpEnabled(true);

@Override
public boolean onOptionsItemSelected(MenuItem item) { 
        switch (item.getItemId()) {
        case android.R.id.home: 
            onBackPressed();
            return true;
        }

    return super.onOptionsItemSelected(item);
}



回答18:


It could be too late to answer but I have a shorter and more functional solution in my opinion.

// Inside your onCreate method, add these.
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);

// After the method's closing bracket, add the following method exactly as it is and voiulla, a fully functional back arrow appears at the action bar
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    onBackPressed();
    return true;
}



回答19:


In oncreate(); write this line->

getSupportActionBar().setDisplayHomeAsUpEnabled(true); 

then implement below method in that class

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
    case android.R.id.home:
        // app icon in action bar clicked; go home
      onBackPressed();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}



回答20:


Manifest.xml

<activity
            android:name=".Activity.SecondActivity"
            android:label="Second Activity"
            android:parentActivityName=".Activity.MainActivity"
            android:screenOrientation="portrait"></activity>



回答21:


Add below code in the onCreate function:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

And then override: @Override public boolean onOptionsItemSelected(MenuItem item){ onBackPressed(); return true; }




回答22:


In your onCreate method add this line

setTitle("Your title");\\if you want to change

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

and add this method to your activity

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }


来源:https://stackoverflow.com/questions/15686555/display-back-button-on-action-bar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!