我發現了一種通過實施一個名爲EditTextPreferenceWithSummary類延伸EditTextPreference並覆蓋一些方法來做到這一點...
public class EditTextPreferenceWithSummary extends EditTextPreference {
public EditTextPreferenceWithSummary(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public EditTextPreferenceWithSummary(Context context) {
super(context);
init();
}
@Override
protected View onCreateView(ViewGroup parent) {
updateSummary();
return super.onCreateView(parent);
}
public void updateSummary()
{
String value = "";
int variation = (this.getEditText().getInputType() & InputType.TYPE_MASK_VARIATION);
Boolean isPassword = ((variation == InputType.TYPE_NUMBER_VARIATION_PASSWORD)
||(variation == InputType.TYPE_TEXT_VARIATION_PASSWORD)
||(variation == InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD));
if (isPassword)
{
value = this.getText().replaceAll(".", "*");
}
else
{
value = this.getText();
}
this.setSummary(value);
}
private void init() {
setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
EditTextPreferenceWithSummary pref = (EditTextPreferenceWithSummary) preference;
pref.updateSummary();
return true;
}
});
}
}
而且我喜歡的XML文件看起來像這樣:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<PreferenceCategory
android:title="@string/pref_header_database">
<com.designit.api.preferences.EditTextPreferenceWithSummary
android:title="@string/field_database_server_ip"
android:defaultValue=""
android:summary="Set the IP adress of the server"
android:key="server_ip_address" />
<com.designit.api.preferences.EditTextPreferenceWithSummary
android:title="@string/field_database_server_port"
android:defaultValue=""
android:inputType="number"
android:summary="Set the port of the server"
android:key="server_port" />
<com.designit.api.preferences.EditTextPreferenceWithSummary
android:title="@string/field_database_name"
android:defaultValue=""
android:summary="Set the database name"
android:key="database_name" />
<com.designit.api.preferences.EditTextPreferenceWithSummary
android:title="@string/field_database_user"
android:defaultValue=""
android:summary="Set the database user"
android:key="database_user" />
<com.designit.api.preferences.EditTextPreferenceWithSummary
android:title="@string/field_database_password"
android:defaultValue=""
android:summary="Set the database password"
android:key="database_passwd"
android:inputType="textPassword"/>
</PreferenceCategory>
希望這可以幫助你。 乾杯。