问题
I am using the viewpageIndicator Library in my application. I am using this sample class in my code.
public class SampleTitlesWithListener extends BaseSampleActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_titles);
mAdapter = new TestFragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TitlePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
//We set this on the indicator, NOT the pager
mIndicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
Toast.makeText(SampleTitlesWithListener.this, "Changed to page " + position, Toast.LENGTH_SHORT).show();
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
My Problem is, In one of the tabs i have toggle button to show the content in List or Grid. I am storing this is in Shared Preferences. How to retrieve this when i open the content tab. I am using differentfragment classes for the tabs. Thanks in Advance
回答1:
You could have a seperate class with static methods
Saving string in shared preferences and retrieve it again anywhere in your app.
public class PreferencesData {
public static void saveString(Context context, String key, String value) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
sharedPrefs.edit().putString(key, value).commit();
}
public static String getString(Context context, String key, String defaultValue) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
return sharedPrefs.getString(key, defaultValue);
}
}
Usage example:
// save anywhere you have a context
PreferencesData.saveString(context, "mynote", "some note");
// retrieve anywhere you have a context
String note = PreferencesData.getString(context, "mynote", "defaultValue");
来源:https://stackoverflow.com/questions/19095585/shared-preferences-in-view-page-indicator