目前我正在研究导航Activity和片段。我正在使用正常工作的content_main布局替换片段。但是当我旋转屏幕时,片段就会消失,导航活动就会显示出来。当我旋转屏幕时,如何保存碎片的状态,当我旋转屏幕然后片段状态将被保存并且不应该消失,当我单击后退按钮时,将显示活动。 这是我的代码:
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.login) {
getFragmentManager().beginTransaction().replace(R.id.frameLayout,new LoginFragment()).addToBackStack(null).commit();
} else if (id == R.id.signup) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
这是我的登录片段:
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_login, container, false);
btnLogin = (Button) view.findViewById(R.id.btn_login);
btnCreateAccount = (Button) view.findViewById(R.id.createAccount);
forgotPassword = (TextView)view.findViewById(R.id.tv_forgotPassword);
et_emailId = (EditText)view.findViewById(R.id.input_email);
et_Password = (EditText)view.findViewById(R.id.input_password);
loginLayout = (ConstraintLayout) view.findViewById(R.id.homeMain);
btnCreateAccount.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getFragmentManager().beginTransaction().replace(R.id.frameLayout, new SignUpFragment()).addToBackStack(null).commit();
}
});
forgotPassword.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getFragmentManager().beginTransaction().replace(R.id.frameLayout,new ForgotPasswordFragment()).addToBackStack(null).commit();
}
});
return view;
}
@Override
public void onStart() {
super.onStart();
Log.e(TAG,"start");
}
@Override
public void onResume() {
super.onResume();
Log.e(TAG,"Resume");
}
@Override
public void onPause() {
super.onPause();
Log.e(TAG,"Pause");
}
@Override
public void onStop() {
super.onStop();
Log.e(TAG,"stop");
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_login:
checkValidation();
break;
}
}
private void checkValidation() {
emailId = et_emailId.getText().toString();
password = et_Password.getText().toString();
if(emailId.equals("") || emailId.length() == 0
|| password.equals("") || password.length() == 0){
Toast.makeText(getActivity(),"All fields are required",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getActivity(),"login code here",Toast.LENGTH_SHORT).show();
}
}