【问题标题】:Android: Back button event in FragmentActivityAndroid:FragmentActivity 中的后退按钮事件
【发布时间】:2013-09-29 18:19:25
【问题描述】:

我有一个 FragmentActivity。 Activity 包含一个片段。
在片段中,有一个按钮,单击时会在中心出现一个图像视图(View.VISIBLE)。
我想要一个后退按钮事件来检查图像视图是否可见,然后隐藏它,否则,继续默认的后退按钮事件。
由于 FragmentActivity 和 Fragment 是独立的类。而且 Fragment 中没有 onBackPressed()。那么我该怎么做呢?我想在 Fragment 类中处理 back 事件。

【问题讨论】:

    标签: android fragment


    【解决方案1】:

    onBackPressed()在Activity中触发时,与你需要的fragment进行通信,查看此链接了解fragment和activity之间如何通信。

    http://developer.android.com/training/basics/fragments/communicating.html

    【讨论】:

      【解决方案2】:
      @Override
      public void onBackPressed() {
      
          // If the fragment is here, let him handle it
          ourFragment.someMethodWeveCreatedToHandleBackPressed();
      
          // If it was not handled by the method above, then let the super do his usual "back"
          if (!handled){
              super.onBackPressed();
          }
      }
      

      【讨论】:

      【解决方案3】:

      为什么不在片段中覆盖onKeyDown 方法?

      @Override
      public boolean onKeyDown(int keyCode, KeyEvent event) {
          if (keyCode == KeyEvent.KEYCODE_BACK) {
              // Check you image view visibility
              if(yourImageView.getVisibility() == View.VISIBLE) {
                    yourImageView.setVisiblity(View.GONE);
                    return true; // This line is important to handle the event here and not in the next receiver
              }
          }
          return super.onKeyDown(keyCode, event);
      }
      

      让我知道它是否对你有用!

      【讨论】:

        【解决方案4】:

        使用 transaction.addToBackStack(null);

        【讨论】:

        • 它不起作用,因为ImageView 在同一个片段内。只有一个片段。
        猜你喜欢
        • 1970-01-01
        • 2012-04-28
        • 2013-03-02
        • 1970-01-01
        • 1970-01-01
        • 2017-03-28
        • 2014-05-24
        • 1970-01-01
        • 2014-12-16
        相关资源
        最近更新 更多