如何保存最后一个片段



我有三个片段,当应用程序启动其显示空白片段时,我在主活动b1上有两个按钮叫下一个按钮,b2叫上一个按钮,我知道应该使用shareprefrences,但我不知道如何将其添加到此代码

public class MainActivity extends AppCompatActivity  {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void b1(View view) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
XFragment fragment = new XFragment();
ft.replace(R.id.mainfragment,fragment);
ft.commit();
}
public void b2(View view) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
YFragment fragment = new YFragment();
ft.replace(R.id.mainfragment,fragment);
ft.commit();
}
}

以下是使用SharedPreference所需的代码

public class MainActivity extends AppCompatActivity  {
SharedPreference pref;
Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
editor = pref.edit();
int fragment_number=pref.getInt("fragment_number", -1); // getting Integer
if(int==1){
//start first fragment
}
if(int==2){
//start second fragment
}
}
public void b1(View view) {
editor.putInt("fragment_number", 1); 
editor.apply();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
XFragment fragment = new XFragment();
ft.replace(R.id.mainfragment,fragment);
ft.commit();
}
public void b2(View view) {
editor.putInt("fragment_number", 2); 
editor.apply();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
YFragment fragment = new YFragment();
ft.replace(R.id.mainfragment,fragment);
ft.commit();
}
}

相关内容

  • 没有找到相关文章

最新更新