這裏是我如何做到這一點,
- 創造條件,在實現它的任何類 收到
onBackPressed()
,如果它處理的方法或否則爲false將返回true的接口。這將確保您的應用程序在您返回false時退出。
- 在
Activity
創建這些接口的堆棧,然後添加任何此類接口的它。
- 覆蓋
onBackPressed()
在您的活動,然後任何時間,它被稱爲,從堆棧一個監聽器和調用自己的onBackPressed()
如果它返回true。如果它返回false,那麼它不會處理onBackPressed()
,因此Activity可以接管並刪除片段或退出應用程序。
這裏是一個樣本實現。
您的活動
public class MyActivity extends Activity {
//a stack of OnBackPressedListeners, stack one when you want it to receive onBackPressed() from
//this activity.
//PS used stack so that by LIFO, the last listener would be the first to be called.
private Stack<OnBackPressedListener> onBackPressedListeners = new Stack<>();
@Override
public void onBackPressed() {
if (!onBackPressedListeners.isEmpty()) {
if (onBackPressedListeners.peek().onBackPressed()) //if interface is handling onBackPressed(), return. Otherwise super would be called below.
return;
}
//if no listeners, then do super. This would ensure natural behaviour such as closing the app or popping a fragment when no listeners are using onBackPressed()
super.onBackPressed();
}
//listener interface
public static interface OnBackPressedListener {
/**
* @return true if you're handling onBackPressed, false otherwise to let super.onBackPressed() take over
*/
public boolean onBackPressed();
}
public void addOnBackPressedListener(OnBackPressedListener listener) {
onBackPressedListeners.add(listener);
}
public void removeOnBackPressedListener(OnBackPressedListener listener) {
onBackPressedListeners.remove(listener);
}
}
在您的片段
//implement OnBackPressedListener in your fragment.
public class MyFragment extends Fragment implements OnBackPressedListener {
//find somewhere to add the listener to your Activity, most likely in onCreateView(...)
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
...
((MyActivity)getActivity()).addOnBackPressedListener(this);
...
return view;
}
//overide onBackPressed(), then return true if you're handling the onBackPressed(), false otherwise.
@Override
public boolean onBackPressed() {
if (slider_call_phones.isOpened()) {
slider_call_phones.closeLayer(true);
return true;
}
return false;
}
//lastly remember to remove the listener when your fragment is destroyed, so that it stops receiving callbacks,
//if you don't do this, you might get a NullPointerException.
@Override
public void onDestroy() {
super.onDestroy();
((MyActivity)getActivity()).removeOnBackPressedListener(this);
}
}
我大多使用單Activity
和一大堆的在我的Android應用Fragment
的,這正是我如何解決您遇到的問題,例如,如果在按下後退按鈕時打開抽屜中的抽屜,或者在退出應用程序時退出應用程序關閉。
此代碼未實現'onBackPressed()'。如果你擺脫了這個代碼,而是實現'onBackPressed()',你可能會有更好的運氣。 – CommonsWare
【如何實現片段onBackPressed()?] @CommonsWare你的意思是(http://stackoverflow.com/questions/5448653/how-to-implement-onbackpressed-in-fragments) –
'onBackPressed'可能的工作重複罰款碎片? –