在开发软件设置界面的时候,我们可以采用android系统提供的PreferenceActivity来实现,下面给出一个简单的例子:
1、Activity 代码如下:
public class ConfigActivity extends PreferenceActivity {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);addPreferencesFromResource(R.xml.config);}@Overridepublic boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,Preference preference) {return super.onPreferenceTreeClick(preferenceScreen, preference);}}
2、config.xml代码如下:
<?xml version="1.0" encoding="utf-8"?><PreferenceScreenxmlns:android="http://schemas.android.com/apk/res/android"><PreferenceCategory android:key="config" android:title="@string/config"><CheckBoxPreference android:key="config_anonymous"android:title="@string/config_anonymous"android:disableDependentsState="true"/><EditTextPreference android:key="config_username"android:title="@string/config_username"android:dependency="config_anonymous"/><EditTextPreference android:key="config_password"android:title="@string/config_password"android:dependency="config_anonymous"/></PreferenceCategory></PreferenceScreen>
3、实现的效果:
(解释:当上面的checkbox值为真,禁用下面的用户名和密码设置,否则开启下面的设置项)
4、关键点:
注意上面代码中的黑色粗体代码,android:dependency="config_anonymous" 这个属性指定该设置项依赖于前面key="config_anonymous" 的CheckBoxPreference的值,
如果config_anonymous的值为真(即选中状态),则config_username和config_password可用,即enabled的,否则为disabled。
但是,现在的逻辑刚好相反,即config_anonymous的值为真的时候,需要禁用下面的config_username和config_password设置项。要实现这个就需要在CheckBoxPreference上设置了,
即添加android:disableDependentsState="true"这个属性,这个属性的意思是,当CheckBoxPreference的值为真的时候,禁用依赖于该设置的其他设置项。
联系客服