在我的android应用中,我有设置活动,该活动使用首选项。

有许多首选项,例如ListPreference, SwitchPreference, etc.,但是我不需要一种首选项。

在此偏好下,我想:
1.显示恒定且永远不变的标题(例如其他首选项)
2.显示文本,该文本将由应用程序更改,但不会由用户更改。

与此最类似的首选项是EditTextPreference,但对我来说并不好,因为我不希望用户更改显示的文本,而是由我的应用程序对其进行更改。因此,我的偏好可以称为TextViewPreference

我想要的一个很好的例子是在“设置” Android应用程序内的“设备信息”类别内。

编辑:
我要用于更改摘要的代码不会放在活动代码中,并且我不使用PreferenceActivity
实际上,只有我必须更改摘要的时间是SettingsActivity不在主线程上。

最佳答案

下面的代码是您要实现的目标的完整示例,它显示了一个示例,该示例说明如何创建一个基于其他首选项(x_pref和y_pref的添加并在下面的result_pref中显示结果)直接更新的信息首选项。基于其他活动传递的信息。

1)DemoActivity ----------

public class DemoActivity extends AppCompatActivity{


@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.demo_activity);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.demo_preferences, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch(item.getItemId()) {
        case R.id.menu_settings:
            Intent i = new Intent(DemoActivity.this , PrefDemoActivity.class);
            i.putExtra("Passed", "Test--##%%&&");
            startActivity(i);
            break;
        default:
            throw new RuntimeException("unknown menu selection");
    }

    return true;
}
}


2)demo_activity.xml ----------

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Empty"
    android:gravity="center"
    android:background="@android:color/holo_blue_light"/>

</android.support.constraint.ConstraintLayout>


3)PrefDemoActivity ----------

public class PrefDemoActivity extends AppCompatActivity {

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    FragmentManager mFragmentManager = getFragmentManager();
    FragmentTransaction mFragmentTransaction = mFragmentManager
            .beginTransaction();
    DemoEditPreferences mDemoPrefsFragment = new DemoEditPreferences();
    mFragmentTransaction.replace(android.R.id.content, mDemoPrefsFragment);
    mFragmentTransaction.commit();

}
}


4)DemEditPreferences ----------

public class DemoEditPreferences extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener{

private SharedPreferences demo_preferences;
private int preferencesToEdit;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    demo_preferences = getActivity().getSharedPreferences("demo_preference",
            0);

    preferencesToEdit = R.xml.demo_preferences;
    String preferenceName = getResources().getString(R.string.pref_sensor_key);

    PreferenceManager preferenceManager = getPreferenceManager();
    preferenceManager.setSharedPreferencesName(preferenceName);
    preferenceManager.setSharedPreferencesMode(0);

    getActivity().setTitle("Demo Preferences");

    addPreferencesFromResource(preferencesToEdit);

    Preference from_another_activity_p = (Preference) findPreference("passed_from_another_activity_key");

    if(getActivity().getIntent() != null) {

        from_another_activity_p.setSummary(getActivity().getIntent().getStringExtra("Passed"));
    }

    updateResult();

    for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {
        initSummary(getPreferenceScreen().getPreference(i));
    }

}


@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

    if(findPreference(key) != null) {

        if(findPreference(key).getKey().equals("x_key")) {

            updateResult();

        }else if(findPreference(key).getKey().equals("y_key")) {


            updateResult();

        }

        checkPrefValueValidity(findPreference(key));
        updatePrefSummary(findPreference(key));
    }

}

private void updateResult(){

    EditTextPreference x_p = (EditTextPreference) findPreference("x_key");
    EditTextPreference y_p = (EditTextPreference) findPreference("y_key");
    Preference result_p = (Preference) findPreference("result_key");
    result_p.setSummary("( X + Y ) = " + (Float.valueOf(x_p.getText()) + Float.valueOf(y_p.getText())));

}

private void initSummary(Preference p) {
    if (p instanceof PreferenceCategory) {
        PreferenceCategory pCategory = (PreferenceCategory) p;
        for (int i = 0; i < pCategory.getPreferenceCount(); i++) {
            initSummary(pCategory.getPreference(i));
        }
    } else {
        updatePrefSummary(p);
    }
}

private void updatePrefSummary(Preference p) {
    if (p instanceof ListPreference) {
        ListPreference listPref = (ListPreference) p;
        p.setSummary(listPref.getEntry());
    }
    if (p instanceof EditTextPreference) {
        EditTextPreference editTextPref = (EditTextPreference) p;
        p.setSummary(editTextPref.getText());
    }
}

private void checkPrefValueValidity(Preference p) {
    if (p instanceof EditTextPreference) {
        EditTextPreference editTextPref = (EditTextPreference) p;
        if (editTextPref.getText().equals("")) {
            // what do you want to do if the value entered is empty
        } else {
            // maybe only certain values are allowed
        }
    }
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = super.onCreateView(inflater, container, savedInstanceState);
    view.setBackgroundColor(getResources().getColor(android.R.color.white));
    return view;
}

@Override
public void onResume() {
    super.onResume();
    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}

@Override
public void onPause() {
    super.onPause();
    getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}

@Override
public void onDestroy() {
    super.onDestroy();
    getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}

}


5)demo_menu ----------

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@+id/menu_settings"
    android:title="Settings"
    android:titleCondensed="Settings"
    android:orderInCategory="1">
</item>

</menu>


7)demo_preferences ----------

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

<PreferenceCategory
    android:title="Demo">

    <EditTextPreference
        android:key="x_key"
        android:title="X"
        android:defaultValue="0"
        android:summary="0"
        android:inputType="numberDecimal|numberSigned"
        android:selectAllOnFocus="true"
        android:singleLine="true">
    </EditTextPreference>

    <EditTextPreference
        android:key="y_key"
        android:title="Y"
        android:defaultValue="0"
        android:summary="0"
        android:inputType="numberDecimal|numberSigned"
        android:selectAllOnFocus="true"
        android:singleLine="true">
    </EditTextPreference>

    <Preference
        android:key="result_key"
        android:title="Result"
        android:summary="0"> // default summary value if any
    </Preference>

    <Preference
        android:key="passed_from_another_activity_key"
        android:title="From another Activity"
        android:summary="null"> // default summary value if any
    </Preference>

</PreferenceCategory>

</PreferenceScreen>


8)不要忘记将两个活动都添加到清单中。

10-06 06:05