Tuesday, August 24, 2010

SeekBar Preference

I just would like to share the code that I've posted in the Google Devs mailing list when someone asked about the SeekBar Preference.
public class SeekBarPreference extends DialogPreference{

private Context context;
private SeekBar volumeLevel;

public SeekBarPreference(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}

protected void onPrepareDialogBuilder(Builder builder) {

LinearLayout layout = new LinearLayout(context);
layout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
layout.setMinimumWidth(400);
layout.setPadding(20, 20, 20, 20);

volumeLevel = new SeekBar(context);
volumeLevel.setMax(32);
volumeLevel.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
volumeLevel.setProgress(Integer.parseInt(getSharedPreferences().getString(getKey(),"32")));

layout.addView(volumeLevel);


builder.setView(layout);

super.onPrepareDialogBuilder(builder);
}

protected void onDialogClosed(boolean positiveResult) {
if(positiveResult){
persistString(volumeLevel.getProgress()+"");
}
}

}


This allows you to popup a seekbar that you can use to adjust some properties like volume, difficulty and other things where a slider would be useful. Then you use it like:


alarmVolume = new SeekBarPreference(this, null);
alarmVolume.setTitle("Volume");
alarmVolume.setSummary("Modify the volume of the alarm");
alarmVolume.setKey(PREF_ALARM_VOLUME);


and then can be added to a PreferenceScreen or PreferenceCategory




1 comment:

Anonymous said...

thanks man !!

u gave me just what i neded .