在android fragment activity中实现返回按钮[重复]

v8wbuo2f  于 2023-03-27  发布在  Android
关注(0)|答案(1)|浏览(137)

此问题在此处已有答案

How to implement onBackPressed() in Fragments?(58回答)
Add back button to action bar(11个答案)
昨天关门了。
我用这个教程来实现facebook登录等。
Facebook Login
我在这个片段中添加了新的片段来显示好友列表。现在当我在新添加的片段上按下后退按钮时,它会将我带到SPLASH片段,我希望在动作栏上的后退按钮上有相同的行为。这意味着当我在新片段上时,它会在动作栏上显示后退按钮。按下后退按钮会将我带回SPLASH屏幕。

private void showFragment(int fragmentIndex, boolean addToBackStack) {
    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction transaction = fm.beginTransaction();
    for (int i = 0; i < fragments.length; i++) {
        if (i == fragmentIndex) {
            transaction.show(fragments[i]);
        } else {
            transaction.hide(fragments[i]);
        }
    }
    if (addToBackStack) {
        transaction.addToBackStack(null);
    }
    transaction.commit();
}
ruarlubt

ruarlubt1#

我得到了这个代码在stackoverflow搜索后努力希望这可能会帮助你

ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);// in on Create()

搜索代码onOptionsItemSelected(MenuItem item)并以这种方式编辑它

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
    case android.R.id.home:
        // change your behaviour here
        Intent intent = new Intent(this, yourclass.class);// i started new activity here
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        return true;
  }
    return super.onOptionsItemSelected(item);
}

相关问题