Android中操作栏的“显示后退"按钮不返回 [英] Display back button of action bar is not going back in Android

查看:300
本文介绍了Android中操作栏的“显示后退"按钮不返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Android应用程序.我正在将ActionBar与AppCompactActivity一起使用.在我的应用程序中,我向操作栏添加后退按钮.但是,当我单击它时,它不会返回到上一个活动.例如,我从活动1开始活动2.活动2包含带后退"按钮的操作栏.但是,当我单击活动2的操作栏上的后退按钮时,它不会返回到活动1.

I am developing an Android app. I am using ActionBar with AppCompactActivity. In my app, I add back button to action bar. But when I click on it, it is not going back to the previous activity. For example, I start activity 2 from activity 1. Activity 2 contains action bar with back button. But when I click on action bar back button of activity 2, it is not going back to activity 1.

这就是我为活动2设置操作栏的方式.

This is how I set action bar for activity 2:

public class EditProfileActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_profile);
        Toolbar toolbar = (Toolbar)findViewById(R.id.profile_action_toolbar);
        setSupportActionBar(toolbar);
        setTitle("Edit Profile");
        ActionBar actionBar= getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
}

这就是我从活动1开始活动2的方式.

This is how I started activity 2 from activity 1:

Intent i = new Intent(MainActivity.this,SecondActivity.class);
                    startActivity(i);

单击此按钮后不会返回

为什么不回头?

推荐答案

在活动中添加以下内容.您必须处理后退按钮的click事件.

Add the following to your activity.You have to handle the click event of the back button.

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

这篇关于Android中操作栏的“显示后退"按钮不返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆