Android SeekBarPreference浅聊
由于网上有很多人问到SeekBarPreference怎么去实现,今天将这个效果做出来,本例子并没有真正的改变屏幕亮度,如果真正想去实现,那么可 以在这个类中onProgressChanged()方法或者onDialogClosed()方法中写上自己调节亮度的代码,并将这些值保存起来。
1.首先定义一个类SeekBarPreference继承于DialogPreference的类:
java代码:
- package eoe.demo;
- import android.content.Context;
- import android.preference.DialogPreference;
- import android.util.AttributeSet;
- import android.util.Log;
- import android.view.View;
- import android.widget.SeekBar;
- import android.widget.TextView;
- import android.widget.SeekBar.OnSeekBarChangeListener;
- public class SeekBarPreference extends DialogPreference implements
- OnSeekBarChangeListener {
- private SeekBar seekBar;
- private TextView textView;
- public SeekBarPreference(Context context, AttributeSet attrs) {
- super(context, attrs);
- // TODO Auto-generated constructor stub
- }
- @Override
- protected void onBindDialogView(View view) {
- // TODO Auto-generated method stub
- super.onBindDialogView(view);
- seekBar = (SeekBar) view.findViewById(R.id.seekBar1);
- textView = (TextView) view.findViewById(R.id.textView1);
- seekBar.setOnSeekBarChangeListener(this);
- }
- @Override
- protected void onDialogClosed(boolean positiveResult) {
- // TODO Auto-generated method stub
- if (positiveResult) {
- Log.i("Dialog closed", "You click positive button");
- } else {
- Log.i("Dialog closed", "You click negative button");
- }
- }
- @Override
- public void onProgressChanged(SeekBar seekBar, int progress,booleanfromUser) {
- textView.setText(progress + "% " + progress + "/100");
- }
- @Override
- public void onStartTrackingTouch(SeekBar seekBar) {
- // TODO Auto-generated method stub
- }
- @Override
- public void onStopTrackingTouch(SeekBar seekBar) {
- // TODO Auto-generated method stub
- }
- }
复制代码
2.以上实现的为一个对话框式的Preference,也就是SeekBar将会旋转在一个DialogPreference上,以下为DialogPreference的dialogLayout文件: http://www.my400800.cn
java代码:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical">
- <SeekBar
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:id="@+id/seekBar1"
- android:layout_marginLeft="20dip"
- android:layout_marginRight="10dip"
- android:max="100"
- android:progress="60">
- </SeekBar>
- <TextView
- android:text="TextView"
- android:id="@+id/textView1"
- android:layout_height="wrap_content"
- android:layout_width="fill_parent"
- android:layout_marginLeft="20dip" >
- </TextView>
- </LinearLayout>
3.将写好的自定义Preference类放到定义preference的xml文件中:
java代码:
- <hz.demo.SeekBarPreference
- android:dialogTitle="亮度调整"
- android:title="调整亮度"
- android:summary="调整屏幕的亮度"
- android:key="light"
- android:dialogLayout="@layout/seekbar">
- </hz.demo.SeekBarPreference>