2016-05-04 11 views
0

FragmentPagerAdapterで戻るボタンを処理するにはどうすればよいですか?私は戻るボタンを押していますが、アプリはアクティビティから外れているので、前のフラグメントに戻る必要があります。FragmentPagerAdapterから戻ってきます

+1

私はちょっとサンプルコードを与えることができます。 – dex

+0

お願い、サンプルコードを教えていただけますか? – cdapalc

+0

答えを確認してください。 – dex

答えて

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