从FragmentPagerAdapter回来

时间:2016-05-04 15:54:32

标签: android android-fragments back-button

如何处理FragmentPagerAdapter中的后退按钮?我按下后退按钮,但应用程序已退出活动,我只想返回上一个片段。

1 个答案:

答案 0 :(得分:0)

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();
}