Shared Preferences in View Page Indicator

自古美人都是妖i 提交于 2019-12-11 19:39:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!