• 【起航计划 028】2015 起航计划 Android APIDemo的魔鬼步伐 27 App->Preferences->Launching preferences 其他activity获取Preference中的值


    前给例子介绍了如何使用PreferenceActivity 来显示修改应用偏好,用户对Preferences的修改自动存储在应用对应的Shared Preferences中。

    本例介绍了如何从一个Activity来取得由PreferenceActivity 的Preference值。 比如在实际应用中通过PreferenceActivity界面来取得用户偏好或是配置。

    因为希望从PreferenceActivity返回值,所以使用startActivityForResult 来启动PreferenceActivity的派生类。

    AdvancedPreferences 为PreferenceActivity 的派生类,它对于的R.xml.advanced_preferences 定义了两个Preferences项,一个是自定义Preference(MyPreference后面有介绍),其值类型为一整数,另一个为 CheckBoxPreference,其UI如下:

    这个例子目的是通过AdvancedPreferences的设置来取得MyPreference的值,MyPreference在R.xml.advanced_preferences的定义如下:

        <com.example.android.apis.preference.MyPreference
                android:key="my_preference"
                android:title="@string/title_my_preference"
                android:summary="@string/summary_my_preference"
                android:defaultValue="100" />

    我们可以看到它的Key定义为my_preference。

    调用AdvancedPreferences 代码如下:

            // When the button is clicked, launch an activity through this intent
            Intent launchPreferencesIntent = new Intent().setClass(this, AdvancedPreferences.class);
    
            // Make it a subactivity so we know when it returns
            startActivityForResult(launchPreferencesIntent, REQUEST_CODE_PREFERENCES);

    处理AdvancedPreferences返回:

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
    
            // The preferences returned if the request code is what we had given
            // earlier in startSubActivity
            if (requestCode == REQUEST_CODE_PREFERENCES) {
                // Read a sample value they have set
                updateCounterText();
            }
        }
    
        private void updateCounterText() {
            // Since we're in the same package, we can use this context to get
            // the default shared preferences
            SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
            final int counter = sharedPref.getInt(AdvancedPreferences.KEY_MY_PREFERENCE, 0);
            mCounterText.setText(getString(R.string.counter_value_is) + " " + counter);
        }

    可以看到取得Shared Preferences某个Preference的值是根据定义它的Key值然后调用 getXXX(key ..)来取得的。

    下图则为从AdvancedPreferences 返回后在 LaunchingPreferences 显示 MyPreference的值。

  • 相关阅读:
    layer常用方法
    使用GLSL实现更多数量的局部光照 【转】
    GLSL实现简单硬件Anisotrop Lighting 【转】
    Bump mapping的GLSL实现 [转]
    图形化OpenGL调试器 BuGLe [转]
    GLSL实现Fresnel And Chromatic aberration 【转】
    GLSL实现Ambient Occlusion 【转】
    GLSL实现Glow效果 [转]
    2013年中国区Skyline软件价格体系
    [OSG]如何用Shader得到物体的世界坐标
  • 原文地址:https://www.cnblogs.com/dongdong230/p/4323000.html
Copyright © 2020-2023  润新知