使"up"状态按钮的行为类似于“后退"按钮Android上的按钮

问题描述:

我正在使用的Android应用程序设计要求向上"按钮的行为与后退"按钮的行为相同,但我不确定如何实现.

The Android app design I'm working with calls for the "Up" button to behave the same way the "Back" button behaves, but I'm not sure how to make that happen.

我知道必须为在活动上可见的向上"按钮指定android:parentActivityName,但是指定固定的父活动对于该活动实际上没有任何意义.想象一下活动A,活动B和活动C的情况:

I know that android:parentActivityName must be specified for the "Up" button to be visible on an activity, but specifying a fixed parent activity doesn't really make sense for the activity. Imagine this scenario with activities A, B, and C:

  1. 启动活动A,它包含两个按钮:每个按钮分别带您进入活动B和C.
  2. 点击活动B的按钮.
  3. 转换为活动B.它包含两个按钮:每个按钮分别将您带到活动A和C.
  4. 点击活动C的按钮.
  5. 转换为活动C.
  6. 点击向上"按钮,您进入活动B.
  7. 现在在活动B上:点击活动A的按钮.
  8. 过渡到活动A.
  9. 点击向上"按钮,您进入活动B.
  10. 在活动B上,点击向上"按钮,您进入活动A.
  11. 现在在活动A上:点击活动C的按钮.
  12. 转换为活动C.
  13. 点击向上"按钮,您进入活动A.
  1. Launch into activity A, it contains two buttons: each taking you to activities B and C, respectively.
  2. Tap the button for activity B.
  3. Transition to activity B. it contains two buttons: each taking you to activities A and C, respectively.
  4. Tap the button for activity C.
  5. Transition to activity C.
  6. Tap the "up" button, you should be taken to activity B.
  7. On activity B now: tap the button for activity A.
  8. Transition to activity A.
  9. Tap the "up" button, you should be taken to activity B.
  10. On activity B Tap the "up" button, you should be taken to activity A.
  11. On activity A now: tap the button for activity C.
  12. Transition to activity C.
  13. Tap the "up" button, you should be taken to activity A.

如果我要为每个活动指定android:parentActivityName,则将B和C的父活动设为A可能是有意义的,但这意味着每次我们从活动B或C按下向上"按钮时,我们都会降落在活动A中(这并不总是应该发生的).

If I were to specify android:parentActivityName for each activity, it might make sense to have B and C's parent activity be A, but this means that each time we hit the "up" button from activities B or C, we land at activity A (and that's not always what is supposed to happen).

有人对这种事情有经验吗?

Does anybody have experience with this type of thing?

添加以下内容

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

    return(super.onOptionsItemSelected(item));
}

当您按下应用程序上的向上按钮时,它将调用ID为android.R.id.homeonOptionsItemSelected,只是遇到这种情况并手动调用onBackPressed()

when you press the up button on your app it will invoke onOptionsItemSelected with the id of android.R.id.home just catch that case and manually call onBackPressed()