这是我的活动课
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
username = getIntent().getStringExtra("username");
password = getIntent().getStringExtra("password");
DashbordFragment f = new DashbordFragment();
Bundle b = new Bundle();
b.putString("username",username);
b.putString("password",password);
f.setArguments(b);
创建一个片段并使用bundle将其传递给片段f
DashbordFragment fragment = f;
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
点击菜单项时更改片段
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
Fragment fragment=null;
if(id == R.id.nav_dashboard){
fragment = new DashbordFragment();
}
else if (id == R.id.nav_inbox){
fragment = new InboxFragment();
}
if (fragment != null) {
android.support.v4.app.FragmentTransaction
fragmentTransaction =
getSupportFragmentManager().beginTransaction();
这是为了替换
fragmentTransaction.replace(R.id.fragment_container,
fragment);
fragmentTransaction.commit();
}
DrawerLayout drawer = (DrawerLayout)
findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return false;
}
答案 0 :(得分:0)
您是否尝试在FragmentClass上添加或覆盖saveInstanceState?仅当您想依赖存储状态时才建议您使用实例变量
@Override public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save some state!
}
答案 1 :(得分:0)
您可以在应用程序中使用共享首选项来存储用户名和密码。通过使用它,您可以随时随地访问整个应用程序中保存的数据。
这将为您提供相同的基本概念:Shared Preference
保存数据:
SharedPreferences.Editor editor =
getActivity().getSharedPreferences(prefKey, MODE_PRIVATE).edit();
editor.putString("username", "abc");
editor.putString("password", "123");
editor.apply();
要检索数据:
SharedPreferences prefs = getActivity().getSharedPreferences(prefKey,
MODE_PRIVATE);
if (prefs.contains("username")&&(prefs.contains("password"))){
String userName= prefs.getString("username",null);
String usrPassword = prefs.getString("paswword",null);
if((userName!=null) && (usrPassword!= null)) {
//whatever you need to do with the obtained data
}
}