重寫返回鍵(Fragment)

荒謬c發表於2018-05-10
自定義 BackHandledFragment類
判斷是Fragment,按下返回鍵返回上一個Fragment(頁面)
     public abstract class BackHandledFragment extends Fragment {

         protected BackHandledInterface mBackHandledInterface;

/** 
 * 所有繼承BackHandledFragment的子類都將在這個方法中實現物理Back鍵按下後的邏輯 
 * FragmentActivity捕捉到物理返回鍵點選事件後會首先詢問Fragment是否消費該事件 
 * 如果沒有Fragment訊息時FragmentActivity自己才會消費該事件 
 */

 
        public abstract boolean onBackPressed();  

        @Override  
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);  
            if(!(getActivity() instanceof BackHandledInterface)){
                throw new ClassCastException("Hosting Activity must implement BackHandledInterface");  
            }else{  
                this.mBackHandledInterface = (BackHandledInterface)getActivity();  
            }  
        }  

        @Override  
        public void onStart() {  
            super.onStart();  
            //告訴FragmentActivity,當前Fragment在棧頂  
            mBackHandledInterface.setSelectedFragment(this);  
        }

        public interface BackHandledInterface {
            void setSelectedFragment(BackHandledFragment selectedFragment);
                }

        }
        
        
        
        
        
         在實現的Fragment 中 繼承  BackHandledFragment類
        //重寫返回鍵,判斷是Fragment,按下返回鍵返回上一個Fragment(頁面)
        @Override
        public boolean onBackPressed() {

            if (stockption_webView.canGoBack()) {
                stockption_webView.goBack();
               L.e("webView.goBack()", "webView.goBack()");

                return true;

            } else {
                L.e("Conversatio退出", "Conversatio退出");

                return false;
            }
        }





            在實現的Fragment的 Activity 中 實現 implements BackHandledFragment.BackHandledInterface
                    @Override
              public void onBackPressed() {
             if(mBackHandedFragment == null || !mBackHandedFragment.onBackPressed()){
              if(getSupportFragmentManager().getBackStackEntryCount() == 0){
              super.onBackPressed(); //退出
             }else{
              getSupportFragmentManager().popBackStack(); //fragment 出棧
          }
        }
      }

 

 

複製程式碼
//重寫返回鍵,判斷是Fragment,按下返回鍵返回上一個Fragment(頁面)
@Override
public boolean onBackPressed() {

    if (stockption_webView.canGoBack()) {
        stockption_webView.goBack();
        L.e("webView.goBack()", "webView.goBack()");

        return true;

    } else {
        L.e("Conversatio退出", "Conversatio退出");

        return false;
    }
}
複製程式碼

相關文章