我正在尝试将用户在下面的登录屏幕上输入的名称保存Settings.java
到 asharedPreference
中,该名称将由TestFragment2.java
从另一个 FragmentActivity 调用的 读取,SampleTabsDefault.java
设置.java
private void savePrefs(String key, boolean value) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
edit.putBoolean(key, value);
edit.commit();
}
private void savePrefs(String key, String value) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
edit.putString(key, value);
edit.commit();
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
savePrefs("CHECKBOX", cb.isChecked());
if (cb.isChecked())
savePrefs("NAME", et.getText().toString());
Intent myIntent = new Intent("com.test.SAMPLETABSDEFAULT");
startActivity(myIntent);
finish();
}
}
Intent myIntent = new Intent("com.test.SAMPLETABSDEFAULT");startActivity(myIntent);
加载SampleTabsDefault.java
就好了,它调用的所有片段也是如此。
class NavTabs extends FragmentPagerAdapter {
public NavTabs(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch(position)
{
case 0:
TestFragment fragment = new TestFragment();
return fragment;
case 1:
TestFragment2 fragment2 = new TestFragment2();
return fragment2;
}
TestFragment3 fragment3 = new TestFragment3();
return fragment3;
}
我可以左右滚动并进入下面看到的片段 TestFragment2.java....但是它没有读取,或者我正在应用sharedPreferences
内部TestFragment2.java
TestFragment2.java做出非常愚蠢的举动
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_2, container, false);
text = (TextView)myView.findViewById(R.id.textView1);
et = (TextView)myView.findViewById(R.id.textView3);
cb = (CheckBox) myView.findViewById(R.id.checkBox1);
loadPrefs();
return myView;
}
private void loadPrefs() {
SharedPreferences sp = getActivity().getSharedPreferences("CHECKBOX", 0);
boolean cbValue = sp.getBoolean("CHECKBOX", false);
String name = sp.getString("NAME", "YourName");
if(cbValue){
cb.setChecked(true);
}else{
cb.setChecked(false);
}
et.setText(name);
}
在TestFragment2.java
我试图textView
通过 'setText();'阅读和申请 sharedPreferences 与我在Settings.java
. 中的代码Settings.java
确实有效,String name = sp.getString("NAME", "YourName");
它加载sharedPreference
并显示用户上次运行应用程序时输入的名称,但在 TestFragmnet2.java
同一代码块中返回 YourName fromString name = sp.getString("NAME", "YourName");
非常感谢任何帮助,谢谢!