简体   繁体   English

在操作栏上显示后退按钮

[英]Display back button on action bar

I'm trying to display a Back button on the Action bar to move previous page/activity or to the main page (first opening).我正在尝试在Action bar上显示Back button以移动上一页/活动或主页面(第一次打开)。 And I can not do it.而我做不到。

my code.我的代码。

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

the code is in onCreate .代码在onCreate

well this is simple one to show back button嗯,这是一个简单的显示后退按钮的按钮

actionBar.setDisplayHomeAsUpEnabled(true);

and then you can custom the back event at onOptionsItemSelected然后您可以在 onOptionsItemSelected 自定义返回事件

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

I think onSupportNavigateUp() is the best and Easiest way to do so, check the below steps.我认为onSupportNavigateUp()是最好和最简单的方法,请检查以下步骤。 Step 1 is necessary, step two have alternative.第一步是必须的,第二步可以选择。

Step 1 showing back button: Add this line in onCreate() method to show back button.步骤 1 显示后退按钮:onCreate()方法中添加此行以显示后退按钮。

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

Step 2 implementation of back click: Override this method Step 2 back click的实现:重写这个方法

@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或步骤 2 替代方法:您可以将元添加到清单文件中的活动中

<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编辑:如果您不使用AppCompat Activity 则不要使用support词,您可以使用

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

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

Thanks to @atariguy for comment.感谢@atariguy 发表评论。

The magic happens in onOptionsItemSelected .神奇发生在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);
    }
}

Official solution官方解决方案

Add those two code snippets to your SubActivity将这两个代码片段添加到您的 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.将元数据和 parentActivity 添加到清单以支持较低的 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参考这里: http : //developer.android.com/training/implementing-navigation/ancestral.html

Add these lines to onCreate()将这些行添加到 onCreate()

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

and in onOptionItemSelected并在 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..!希望对你有帮助..!

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;
}

On your onCreate method add:在您的onCreate方法上添加:

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):AndroidManifest.xml定义父活动(按下操作栏中的后退按钮后将调用的活动):

In your <activity> definition on the Manifest, add the line:在 Manifest 的<activity>定义中,添加以下行:

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

In your onCreate() method add this line在您的onCreate()方法中添加这一行

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

and, in the same Activity, add this method to handle the button click并且,在同一个Activity中,添加这个方法来处理按钮点击

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        this.finish();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

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)将元数据标签添加到AndroidManifest.xml (让系统知道)

 <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接下来,在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来源: Android 开发者文档

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.我知道上面有很多有用的解决方案,但是这次我读了这篇文章(当前的 Android Studio 2.1.2 with sdk 23)上面的某些方法不起作用。

Below is my solution for sub-activity is MapsActivity下面是我对子活动的解决方案是 MapsActivity

First, you need to add parentActivity in首先,您需要在

AndroidManifest.xml 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.其次,确保您的子活动扩展AppCompatActivity ,而不是 FragmentActivity 。

Third, override onOptionsItemSelected() method三、重写onOptionsItemSelected()方法

@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!希望这会有所帮助!

This is simple and works for me very well这很简单,对我很有效

add this inside onCreate() method将此添加到 onCreate() 方法中

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

add this outside oncreate() method在 oncreate() 方法之外添加这个

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

Try this, In your onCreate()试试这个,在你的 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);
        }
    }

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"第 1 步:转到AndroidManifest.xml并在<activity>标签中添加此参数 - 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第 2 步:在ActivityDetail为上一页/ ActivityDetail添加您的action

Example:例子:

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

in onCreate method write-在 onCreate 方法中写入-

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-这是xml文件-

<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并在styles.xml中将其更改为

Theme.AppCompat.Light.NoActionBar

this is all what we have to do.这就是我们所要做的。

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();
}

In oncreate();在 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);
    }
}

Manifest.xml清单文件

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

In Order to display action bar back button in Kotlin there are 2 way to implement it为了在 Kotlin 中显示操作栏后退按钮,有两种实现方式

1. using the default Action Bar provided by Android - Your activity must use a theme that has Action Bar - eg: Theme.AppCompat.Light.DarkActionBar 1. 使用 Android 提供的默认操作栏- 您的活动必须使用具有操作栏的主题 - 例如:Theme.AppCompat.Light.DarkActionBar

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val actionBar = supportActionBar
    actionBar!!.title = "your title"
    actionBar.setDisplayHomeAsUpEnabled(true)
    //actionBar.setDisplayHomeAsUpEnabled(true)
}

override fun onSupportNavigateUp(): Boolean {
    onBackPressed()
    return true
}

2. Design your own Action Bar - disable default Action Bar - eg: Theme.AppCompat.Light.NoActionBar - add layout to your activity.xml 2. 设计您自己的操作栏- 禁用默认操作栏 - 例如:Theme.AppCompat.Light.NoActionBar - 将布局添加到您的 activity.xml

    <androidx.appcompat.widget.Toolbar
     android:id="@+id/main_toolbar"
     android:layout_width="match_parent"
     app:layout_constraintEnd_toEndOf="parent"
     app:layout_constraintStart_toStartOf="parent"
     app:layout_constraintTop_toTopOf="parent">

     <androidx.constraintlayout.widget.ConstraintLayout
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         tools:layout_editor_absoluteX="16dp">

         <TextView
             android:id="@+id/main_toolbar_title"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:text="Your Title"
             android:textSize="25sp"
             app:layout_constraintBottom_toBottomOf="parent"
             app:layout_constraintEnd_toEndOf="parent"
             app:layout_constraintHorizontal_bias="0.5"
             app:layout_constraintStart_toStartOf="parent"
             app:layout_constraintTop_toTopOf="parent" />

     </androidx.constraintlayout.widget.ConstraintLayout>
 </androidx.appcompat.widget.Toolbar>

  • onCreate在创建
override fun onCreate(savedInstanceState: Bundle?) {
     super.onCreate(savedInstanceState)

     setSupportActionBar(findViewById(R.id.main_toolbar))
 }
  • create your own button创建自己的按钮
<?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" >

 <item
     android:id="@+id/main_action_toolbar"
     android:icon="@drawable/ic_main_toolbar_item"
     android:title="find"
     android:layout_width="80dp"
     android:layout_height="35dp"
     app:actionLayout="@layout/toolbar_item"
     app:showAsAction="always"/>

</menu>
  • in YourActivity.kt在 YourActivity.kt 中
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
     menuInflater.inflate(R.menu.main_toolbar_item, menu)

     leftToolbarItems = menu!!.findItem(R.id.main_action_toolbar)
     val actionView = leftToolbarItems.actionView
     val badgeTextView = actionView.findViewById<TextView>(R.id.main_action_toolbar_badge)
     badgeTextView.visibility = View.GONE

     actionView.setOnClickListener {
         println("click on tool bar")
     }
     return super.onCreateOptionsMenu(menu)
 }

In my case;就我而言; I just had to add android:parentActivityName attr to my activity like this:我只需要像这样将android:parentActivityName attr 添加到我的活动中:

<activity
 android:name=".AboutActivity"
 android:label="@string/title_activity_about"
 android:parentActivityName=".MainActivity" />

and the back button appears and works as expected.后退按钮出现并按预期工作。

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);
}
 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;
}
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);
}

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;
}

Add below code in the onCreate function:在 onCreate 函数中添加以下代码:

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

And then override: @Override public boolean onOptionsItemSelected(MenuItem item){ onBackPressed();然后覆盖:@Override public boolean onOptionsItemSelected(MenuItem item){ onBackPressed(); return true;返回真; } }

In updated version getActionBar() does not work!在更新版本中 getActionBar() 不起作用!

Instead, you can do this by this way相反,你可以通过这种方式做到这一点

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

add back button in android title bar this helps you in 2020 在 android 标题栏中添加后退按钮,这将在 2020 年为您提供帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM