【问题标题】:onBackPressed always return to WebView not activityonBackPressed 总是返回 WebView 而不是活动
【发布时间】:2014-08-09 14:49:54
【问题描述】:

我的 Fragment 上有一个 WebView。但是,我想在“onBackPressed()”上调用一个方法,而不是调用 goBack 我的 WebView。当我点击返回按钮时,我的 WebView 总是返回到上一页,根本不调用我的方法。

  @Override
  public void onBackPressed() {
    if (getSupportFragmentManager().findFragmentByTag("myTag") != null) {
        if(myWebView.canGoBack())
           //myWebView.goBack();
        }else {
          super.onBackPressed();
          saveAllData();
        }
    }else{
       super.onBackPressed();
       saveAllData();
    }
 }

我尝试了不同的方法,但它不起作用,见下文: 编辑 1:

在我的 Fragment1 上:

 public void backButtonWasPressed() {
      saveAllData();
 }

关于我的活动:

 @Override
 public void onBackPressed() {
      super.onBackPressed();
      FragmentManager fm = getSupportFragmentManager();
      TopicFragment fragment1 = (TopicFragment)fm.findFragmentById(R.id.content_frame);
      fragment1.backButtonWasPressed();
 }

请帮忙。

谢谢

【问题讨论】:

  • 你应该把 saveAllData() 放在 onPause 中。
  • 但它是如何在BackPressed() 上工作的?我想要的是当用户点击设备上的后退按钮时,然后 saveAllData() 执行。

标签: android android-fragments methods android-webview back-button


【解决方案1】:

这是因为您将片段添加到后台堆栈。所以在提交片段事务之前添加这段代码

transaction.addToBackStack(null);

示例:

// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

【讨论】:

  • 我有 addToBackStack(null),即使我不使用 BackStack。我的 WebView 仍然集中,当我点击后退按钮时,我的 WebView 返回上一页。
  • 我有备用代码,请参阅上面的编辑 1。而且还是不行。
猜你喜欢
  • 2013-04-23
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 2018-05-29
  • 2014-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多