質問

I'm trying to do a settings activity in my app, and I was wondering how can I do a preference that allow the user to change the background color.

I have already done the settings activity, and I was thinking of doing a subsetting when the user clicks on the "Color" option, that shows various colors that the user can set (or, even better, with a palette with all the colors available).

How can I realize that?

役に立ちましたか?

解決

well if you have already created settings activity, it would be something similar to this

public class NormalSettingsActivity extends PreferenceActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.normal_preferences);
    }
}

in your preferences xml add preference category like this

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

    <PreferenceCategory android:title="Background Color Settiongs" >
        <ListPreference
            android:defaultValue="#111111"
            android:entries="@array/colorName"
            android:entryValues="@array/colorCode"
            android:key="background_color"
            android:summary="Set background color of app"
            android:title="Colors" />
    </PreferenceCategory>
</PreferenceScreen>

then in values folder create a xml called arrays

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="colorName">
        <item name="0">Red</item>
        <item name="1">Black</item>
        <item name="2">Yellow</item>
        <item name="3">White</item>
    </string-array>
    <string-array name="colorCode">
        <item name="0">#ff0000</item>
        <item name="1">#111111</item>
        <item name="2">#ffff33</item>
        <item name="3">#ffffff</item>
    </string-array>
</resources>

then in your activity, simply set background color using

backgroundLayout.setBackgroundColor(Color.parseColor(mPreferenceManager.getDefaultSharedPreferences().getString("background_color", "#111111")));

here "background_color" is coming from preferences xml (android:key="background_color")

"#111111" is some default color that will be set if no match found

don't forget to create a global variable

protected PreferencesManager mPreferenceManager;

and initialize it in onCreate, as

mPreferenceManager = PreferencesManager.instance(this);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top