是否有一种方法,我们可以实现onBackPressed()在Android片段类似的方式,我们实现在Android活动?
因为Fragment的生命周期没有onBackPressed()。在android3.0片段中是否有其他替代方法来覆盖onBackPressed() ?
是否有一种方法,我们可以实现onBackPressed()在Android片段类似的方式,我们实现在Android活动?
因为Fragment的生命周期没有onBackPressed()。在android3.0片段中是否有其他替代方法来覆盖onBackPressed() ?
当前回答
这很简单,如果你有一个活动A,你做了3个片段,如B,C和D。现在,如果你在片段B或C和onBackPressed你想移动到片段D每次。然后你必须重写onBackPressed()方法在主活动A,也当你跳转到任何片段,然后传递一个标签或名称的片段,通过你识别的片段在主活动A。
我举了一个例子,通过这个例子你可以很容易地理解....
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, new C_fragment(),"xyz").commit();
}
或者如果你正从片段B移动到片段C,在背按时你想要进入片段D…像下面的
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getActivity().getSupportFragmentManager().beginTransaction().add(R.id.container, new C_frament(), "xyz").commit();
((ActionBarActivity) getActivity()).getSupportActionBar().setTitle("Fragment C");
}
});
现在你必须重写主活动....中的onBackPressed()方法像下面. .
@Override
public void onBackPressed() {
FragmentManager fragmentManager =getSupportFragmentManager();
if (((C_fragment) getSupportFragmentManager().findFragmentByTag("xyz")) != null && ((C_fragment) getSupportFragmentManager().findFragmentByTag("xyz")).isVisible()) {
Fragment fragment = new D_Fragment();
fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
getSupportActionBar().setTitle("D fragment ");
} else {
super.onBackPressed();
}
}
其他回答
新的和更好的方法:以下片段中的代码段将帮助您捕获反按事件。
JAVA
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
OnBackPressedCallback callback = new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
Toast.makeText(mContext, "back pressed", Toast.LENGTH_SHORT).show();
// And when you want to go back based on your condition
if (yourCondition) {
this.setEnabled(false);
requireActivity().onBackPressed();
}
}
};
requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
}
科特林
activity?.onBackPressedDispatcher?.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
}
})
如果你使用EventBus,它可能是一个更简单的解决方案:
在你的片段中:
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
EventBus.getDefault().register(this);
}
@Override
public void onDetach() {
super.onDetach();
EventBus.getDefault().unregister(this);
}
// This method will be called when a MessageEvent is posted
public void onEvent(BackPressedMessage type){
getSupportFragmentManager().popBackStack();
}
在你的Activity类中你可以定义:
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
// This method will be called when a MessageEvent is posted
public void onEvent(BackPressedMessage type){
super.onBackPressed();
}
@Override
public void onBackPressed() {
EventBus.getDefault().post(new BackPressedMessage(true));
}
java只是一个POJO对象
这是超级干净的,没有接口/实现的麻烦。
以下是我对这个问题的解决方案:
活动A:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_CODE)
{
if(resultCode == Activity.RESULT_OK)
{
tvTitle.setText(data.getExtras().getString("title", ""));
}
}
}
活动B:
@Override
public void onBackPressed()
{
setResult(Activity.RESULT_OK, getIntent());
super.onBackPressed();
}
活动b保存片段。
在片段:
private void setText(String text)
{
Intent intent = new Intent();
intent.putExtra("title", text);
getActivity().setIntent(intent);
}
通过这种方式,活动A中的意图对象“data”将从片段中获取字符串
我只是使用findFragmentById和转换到片段,并调用处理onBackpressed的方法。这个示例显示了检查这是否是订单流程的第一步,如果弹出一个对话框片段来确认退出订单。
@Override
public void onBackPressed() {
//check if first fragment in wizard is loaded, if true get abandon confirmation before going back
OrderFragment frag =(OrderFragment)getSupportFragmentManager().findFragmentById(R.id.fragContainer);
if (frag==null || (frag!=null && frag.getOrderStage()<1)){
AlertDialogFragment.show(getSupportFragmentManager(), R.string.dialog_cancel_order,R.string.dialog_cancel_order_msg, R.string.dialog_cancel_order_pos,R.string.dialog_order_quiz_neg, DIALOG_ID_CANCEL);
}else {
super.onBackPressed();
}
}
在我看来,最好的解决办法是:
JAVA解决方案
创建简单的界面:
public interface IOnBackPressed {
/**
* If you return true the back press will not be taken into account, otherwise the activity will act naturally
* @return true if your processing has priority if not false
*/
boolean onBackPressed();
}
在你的活动中
public class MyActivity extends Activity {
@Override public void onBackPressed() {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.main_container);
if (!(fragment instanceof IOnBackPressed) || !((IOnBackPressed) fragment).onBackPressed()) {
super.onBackPressed();
}
} ...
}
最后在你的片段中:
public class MyFragment extends Fragment implements IOnBackPressed{
@Override
public boolean onBackPressed() {
if (myCondition) {
//action not popBackStack
return true;
} else {
return false;
}
}
}
芬兰湾的科特林解决方案
1 -创建接口
interface IOnBackPressed {
fun onBackPressed(): Boolean
}
2 -准备你的活动
class MyActivity : AppCompatActivity() {
override fun onBackPressed() {
val fragment =
this.supportFragmentManager.findFragmentById(R.id.main_container)
(fragment as? IOnBackPressed)?.onBackPressed()?.not()?.let {
super.onBackPressed()
}
}
}
3 -实现在你的目标片段
class MyFragment : Fragment(), IOnBackPressed {
override fun onBackPressed(): Boolean {
return if (myCondition) {
//action not popBackStack
true
} else {
false
}
}
}