这是回答我问题的帖子。对于一个 Android 新手来说,这告诉我一切都需要去哪里。
https://stackoverflow.com/a/30865486/2640458
需要从其活动中查看 onBackPress() 方法的片段:
public class RatingFragment extends Fragment implements ContentActivity.OnBackPressedListener {
@Override
public void doBack() {
getFragmentManager().popBackStack();
}
上面Fragment中对监听器的非常重要的订阅:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_rating, container, false);
((ContentActivity)getActivity()).setOnBackPressedListener(this);
}
需要向上述Fragment发送onBackPress()方法的Activity:
public class ContentActivity extends Activity {
protected OnBackPressedListener onBackPressedListener;
public interface OnBackPressedListener {
void doBack();
}
public void setOnBackPressedListener(OnBackPressedListener onBackPressedListener) {
this.onBackPressedListener = onBackPressedListener;
}
@Override
public void onBackPressed() {
if (onBackPressedListener != null)
onBackPressedListener.doBack();
else
super.onBackPressed();
}
@Override
protected void onDestroy() {
onBackPressedListener = null;
super.onDestroy();
}
}