【问题标题】:can't go back to previous page无法返回上一页
【发布时间】:2020-09-26 15:20:38
【问题描述】:

我创建了一个设置活动。当用户单击设置时,它会从 mainactivity 移动到 settingsactivity,但是当我单击操作栏顶部的后退按钮时,它不会转到上一页,它说应用程序一直在停止。如果我点击手机后退按钮,它会起作用。

在这里我附上了我的编码更正它。我该怎么做?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.settings_activity);
    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.settings, new SettingsFragment())
            .commit();
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home) {
        NavUtils.navigateUpFromSameTask(this);
    }
    return super.onOptionsItemSelected(item);
}

public static class SettingsFragment extends PreferenceFragmentCompat {
   @Override
   public void onCreatePreferences(Bundle savedInstanceState, String rootKey) 
   {
       setPreferencesFromResource(R.xml.root_preferences, rootKey);
   }

}

【问题讨论】:

    标签: android settings


    【解决方案1】:

    最好在活动中使用finish(),因为它会自动返回到上一个活动。

    【讨论】:

      【解决方案2】:

      首先,在 XML 文件中添加 tollbar

          <androidx.appcompat.widget.Toolbar
              android:id="@+id/toolbar"
              android:layout_width="match_parent"
              android:layout_height="?attr/actionBarSize"
              android:background="?attr/colorPrimary" >
              <ImageView
                  android:id="@+id/home"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:src="@drawable/ic_back"/>
          </androidx.appcompat.widget.Toolbar>
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-02
        • 2015-04-21
        • 1970-01-01
        • 2010-12-09
        相关资源
        最近更新 更多