Search code examples
androidcolor-pickerpreferenceactivity

How can I use another Color Picker without preferenceActivity?


I have a color picker which I use in sharedPrefereces. With the default colorpicker I managed to acheive what I want, but I noticed there is no black or white colors. http://www.yougli.net/android/a-photoshop-like-color-picker-for-your-android-application/ I would like to use this code but in the last rows, he shows an example, where I can see it is attached to a preferenced Screen. Instead of it I use my own activity with buttons where using shared Preferences I can save datas/values (so its not a preferenceActivity, just an Activity). For example clicking on a layout results:

OptVertexColor = (LinearLayout) findViewById(R.id.OptVC);
        OptVertexColor.setOnClickListener(new View.OnClickListener() {
        @Override
            public void onClick(View v) {
            LoadChartVertexColor(); 
                ColorPickerDialog dlg = new ColorPickerDialog(settings.this,
                            new ColorPickerDialog.OnColorChangedListener() {
                        public void colorChanged(int color) {
                          SaveChartVertexColor("vertexcolor", color);
                        }
                    }, loadedVertexColor);
                    dlg.setTitle("Select new color");

                    dlg.show();
                }
        }); 

The default color picker dialog appears and I can save a color. Now how can I use this without a preference screen and acheive the same thing? I tried to copy the code above to this code, but I coudnt figure out how to handle it.

public class MySettings extends PreferenceActivity implements OnPreferenceClickListener, ColorPickerDialog.OnColorChangedListener {

    public boolean onPreferenceClick(Preference pref)

    {

        new ColorPickerDialog(this, this, DROIDS_COLOR_KEY, mPrefs.getInt(DROIDS_COLOR_KEY, DROIDS_COLOR_DEFAULT), DROIDS_COLOR_DEFAULT).show();

        return true;

    }

    public void colorChanged(String key, int color)

    {

        ((PreferenceScreen)this.findPreference(SETTINGS_KEY)).getEditor().putInt(key, color).commit();

    }

}

Thank you in advance!


Solution

  • In your own Activity, add

    implements ColorPickerDialog.OnColorChangedListener
    

    to the class declaration.

    Add to your class body:

     public void colorChanged(String key, int color) {
            //create your SharedPreferences and your SharedPreferences.Editor here
            editor.putInt(key, color);
            editor.commit();    
        }
    

    And in a button click listener add:

    new ColorPickerDialog(this, this, DROIDS_COLOR_KEY, mPrefs.getInt(DROIDS_COLOR_KEY, DROIDS_COLOR_DEFAULT), DROIDS_COLOR_DEFAULT).show();
    

    This should work. Let me know if you I failed to answer your question, and I'll see what I can do.