如果我单击后退按钮(设备后退按钮),我试图从我的各种片段打开主片段。但不是替换片段,应用程序关闭,设备的菜单屏幕出现。我不知道出了什么问题。而且没有错误。请帮帮我..
HomeFragment:
public class HomeFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home, container, false);
return view;
}
OneFragment:
public class OneFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_one, container, false);
OnKeyListener pressed = new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
return false;
}
};
view.setOnKeyListener(pressed);
return view;
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Fragment newFragment = new HomeFragment();
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
transaction.replace(R.id.content_frame, newFragment);
// transaction.addToBackStack(null);
transaction.commit();
return false;
}
return super.getActivity().onKeyDown(keyCode, event);
}
}
我甚至尝试在片段中使用onBackPressed()方法。但没有理想的输出。
twoFragment:
public class TwoFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_two, container, false);
return view;
}
public void onBackPressed() {
Fragment newFragment = new WordFragment();
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
transaction.replace(R.id.content_frame, newFragment);
// transaction.addToBackStack(null);
transaction.commit();
super.getActivity().onBackPressed();
}
}
请帮帮我..告诉我哪里出错了。 我只想要打开哪个片段,点击后退按钮它应该打开homefragment类..答案 0 :(得分:0)
要使用片段处理返回导航,您必须使用:
// Works with either the framework FragmentManager or the
// support package FragmentManager (getSupportFragmentManager).
getSupportFragmentManager().beginTransaction()
.add(detailFragment, "detail")
// Add this transaction to the back stack
.addToBackStack()
.commit();
您可以阅读更多内容 Implementing navigation