首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从FragmentPagerAdapter返回

从FragmentPagerAdapter返回
EN

Stack Overflow用户
提问于 2016-05-04 23:54:32
回答 1查看 244关注 0票数 1

如何处理FragmentPagerAdapter中的后退按钮?我正在按后退按钮,但应用程序将退出活动,我只想返回到前一个片段。

EN

回答 1

Stack Overflow用户

发布于 2016-05-05 00:27:19

代码语言:javascript
复制
Basically we are going to implement Observer pattern here.

Let have public interface which have one method called backButtonPressed and return boolean true or false

public interface HandleBackButtonHandler
{
    boolean backButtonPressed();
}

We will notify the current fragment that back button has been pressed, Please handle it.

Lets have fragment class as follows

public class fragment extend Fragment implement HandleBackButtonHandler
{
    .......

    public boolean backButtonPressed()
    {
        // Do what ever you want to do when user press back button here

        return true // if you want to handle the back button pressed else return false
    }
    ......
}



Lets override onBackPressed method of your activity where you will attach your fragments

@Override
public final void onBackPressed()
{

    HandleBackButtonHandler handlebackButtonViaFragment  = (HandleBackButtonHandler ) Adapter.getCurrentFragment();  // safely typecast as interface is implemented by fragment
    if (handlebackButtonViaFragment != null && handlebackButtonViaFragment. backButtonPressed())
    {
        return // this mean fragment has handle the back button, activity you don’t need to do any action
        }   
    super.onBackPressed();
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37032650

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档