Android记录4--自定义ToggleButton+用SharedPreferences保存用户配置

Android记录4--自定义ToggleButton+用SharedPreferences保存用户配置

2013年8月14日Android记录

很多应用都会有用户设置,用户的一些偏好可以由用户来决定那是应用人性化的体现,在实际开发中很多情况都作成可配置的了,本篇博客要介绍的是一个比较炫的状态按钮切换,我想很多开发者都想做出这样的效果,在这里我也就把自己参与的项目当中的这部分实现,做出Demo来于朋友们分享。

没有图,我感觉就特别不舒服:


这样看没办法看出效果,如果能做出动态图就好了,下次吧。

除了ToggleButton的自定义之外,用户配置的信息也是要保存起来的,每一次启动程序的时候要能保证使用的是之前的配置,而不是默认配置,在这里使用SharedPreferences是最好的选择了。

想要源码的猛戳这里:http://download.csdn.net/detail/wwj_748/5945829


布局文件:
/2013.08.14_ToggleButton_demo/res/layout/settings.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/banner_bg" >

        <TextView
            android:id="@+id/tv_Title"
            android:layout_width="wrap_content"
            android:layout_height="42dp"
            android:layout_centerHorizontal="true"
            android:gravity="center"
            android:text="设置"
            android:textColor="#ffffff"
            android:textSize="22sp" />
    </RelativeLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <LinearLayout
                android:id="@+id/layout_AutoPlay"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/item_short_bg_selector"
                android:gravity="center_vertical" >

                <TextView
                    android:id="@+id/tv_AutoPlay"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="10dp"
                    android:layout_weight="1"
                    android:focusable="false"
                    android:singleLine="true"
                    android:text="自动播放"
                    android:textColor="#7a6f66"
                    android:textSize="18sp" />

                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="10dp" >

                    <ToggleButton
                        android:id="@+id/toggle_AutoPlay"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@drawable/toggle_selector"
                        android:gravity="left|center_vertical"
                        android:paddingLeft="14dp"
                        android:paddingRight="14dp"
                        android:textColor="#ffffff"
                        android:textOff="OFF"
                        android:textOn="ON" />

                    <ImageButton
                        android:id="@+id/toggleButton_AutoPlay"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignRight="@+id/toggle_AutoPlay"
                        android:background="#00000000"
                        android:src="@drawable/progress_thumb_selector" />
                </RelativeLayout>
            </LinearLayout>

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:scaleType="fitXY"
                android:src="@drawable/list_divider" />

            <LinearLayout
                android:id="@+id/layout_StartOnBoot"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/item_short_bg_selector"
                android:gravity="center_vertical" >

                <TextView
                    android:id="@+id/tv_StartOnBoot"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="10dp"
                    android:layout_weight="1"
                    android:focusable="false"
                    android:singleLine="true"
                    android:text="开机自启动"
                    android:textColor="#7a6f66"
                    android:textSize="18sp" />

                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="10dp" >

                    <ToggleButton
                        android:id="@+id/toggle_StartOnBoot"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@drawable/toggle_selector"
                        android:gravity="left|center_vertical"
                        android:paddingLeft="14dp"
                        android:paddingRight="14dp"
                        android:textColor="#ffffff"
                        android:textOff="OFF"
                        android:textOn="ON" />

                    <ImageButton
                        android:id="@+id/toggleButton_StartOnBoot"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignRight="@+id/toggle_StartOnBoot"
                        android:background="#00000000"
                        android:src="@drawable/progress_thumb_selector" />
                </RelativeLayout>
            </LinearLayout>
        </LinearLayout>
    </ScrollView>

</LinearLayout>


哪些selector文件的代码就不贴了,自己看源码吧


Activity文件
/2013.08.14_ToggleButton_demo/src/com/wwj/toggle/Setting.java
package com.wwj.toggle;


import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ToggleButton;

/**
 * 自定义ToggleButton的例子
 * 
 * @author wwj 2013年8月14
 */
public class Setting extends Activity {

	private LinearLayout layout_AutoPlay;
	private LinearLayout layout_StartOnBoot;
	private ToggleButton toggle_AutoPlay;
	private ToggleButton toggle_StartOnBoot;
	private ImageButton toggleButton_AutoPlay;
	private ImageButton toggleButton_StartOnBoot;

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

		// 找到控件
		layout_AutoPlay = (LinearLayout) findViewById(R.id.layout_AutoPlay);
		layout_StartOnBoot = (LinearLayout) findViewById(R.id.layout_StartOnBoot);
		toggle_AutoPlay = (ToggleButton) findViewById(R.id.toggle_AutoPlay);
		toggle_StartOnBoot = (ToggleButton) findViewById(R.id.toggle_StartOnBoot);
		toggleButton_AutoPlay = (ImageButton) findViewById(R.id.toggleButton_AutoPlay);
		toggleButton_StartOnBoot = (ImageButton) findViewById(R.id.toggleButton_StartOnBoot);

		initViews();
		setListeners();
	}

	private void initViews() {
		// 是否自动播放,获取SharePerference保存的用户配置
		boolean isAutoPlay = SettingUtils.get(this, SettingUtils.AUTO_PLAY,
				false);
		toggle_AutoPlay.setChecked(isAutoPlay);
		RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) toggleButton_AutoPlay
				.getLayoutParams();
		if (isAutoPlay) { // 如果是自动播放
			// 调整位置
			params.addRule(RelativeLayout.ALIGN_RIGHT, -1);
			params.addRule(RelativeLayout.ALIGN_LEFT,
					R.id.toggleButton_AutoPlay);
			toggleButton_AutoPlay.setLayoutParams(params);
			toggleButton_AutoPlay
					.setImageResource(R.drawable.progress_thumb_selector);
			toggle_AutoPlay.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
		} else {
			// 调整位置
			params.addRule(RelativeLayout.ALIGN_RIGHT, R.id.toggle_AutoPlay);
			params.addRule(RelativeLayout.ALIGN_LEFT, -1);
			toggleButton_AutoPlay.setLayoutParams(params);
			toggleButton_AutoPlay
					.setImageResource(R.drawable.progress_thumb_off_selector);
			toggle_AutoPlay.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
		}

		boolean isAutostart = SettingUtils.get(this,
				SettingUtils.IS_AUTO_START, true);

		toggle_StartOnBoot.setChecked(isAutostart);
		RelativeLayout.LayoutParams params3 = (RelativeLayout.LayoutParams) toggleButton_StartOnBoot
				.getLayoutParams();
		if (isAutostart) {
			// 调整位置
			params3.addRule(RelativeLayout.ALIGN_RIGHT, -1);
			params3.addRule(RelativeLayout.ALIGN_LEFT, R.id.toggle_StartOnBoot);
			toggleButton_StartOnBoot.setLayoutParams(params3);
			toggleButton_StartOnBoot
					.setImageResource(R.drawable.progress_thumb_selector);

			toggle_StartOnBoot.setGravity(Gravity.RIGHT
					| Gravity.CENTER_VERTICAL);
		} else {
			// 调整位置
			params3.addRule(RelativeLayout.ALIGN_RIGHT, R.id.toggle_StartOnBoot);
			params3.addRule(RelativeLayout.ALIGN_LEFT, -1);
			toggleButton_StartOnBoot.setLayoutParams(params3);
			toggleButton_StartOnBoot
					.setImageResource(R.drawable.progress_thumb_off_selector);

			toggle_StartOnBoot.setGravity(Gravity.LEFT
					| Gravity.CENTER_VERTICAL);
		}
	}

	private void setListeners() {
		toggle_AutoPlay.setOnCheckedChangeListener(new ToggleListener(this,
				"自动播放", toggle_AutoPlay, toggleButton_AutoPlay));
		toggle_StartOnBoot.setOnCheckedChangeListener(new ToggleListener(this,
				"开机自启动", toggle_StartOnBoot, toggleButton_StartOnBoot));

		// UI事件,按钮点击事件
		OnClickListener clickToToggleListener = new OnClickListener() {

			@Override
			public void onClick(View v) {
				toggle_AutoPlay.toggle();
			}
		};

		toggleButton_AutoPlay.setOnClickListener(clickToToggleListener);
		layout_AutoPlay.setOnClickListener(clickToToggleListener);

		// UI事件,按钮点击事件
		OnClickListener clickToToggleAutostartListener = new OnClickListener() {
			public void onClick(View v) {
				toggle_StartOnBoot.toggle();
			}
		};
		toggleButton_StartOnBoot
				.setOnClickListener(clickToToggleAutostartListener);
		layout_StartOnBoot
				.setOnClickListener(clickToToggleAutostartListener);
	}

}

工具类:
/2013.08.14_ToggleButton_demo/src/com/wwj/toggle/SettingUtils.java
package com.wwj.toggle;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;

public class SettingUtils {
	public static final String AUTO_PLAY = "auto_play";	// 自动播放
	public static final String IS_AUTO_START = "is_auto_start";	// 开机自启动
	
	
	/**
	 * 获取配置
	 * @param context
	 * @param name
	 * @param defaultValue
	 * @return
	 */
	public static boolean get(Context context, String name, boolean defaultValue) {
		final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		boolean value = prefs.getBoolean(name, defaultValue);
		return value;
	}
	
	/**
	 * 保存用户配置
	 * @param context
	 * @param name
	 * @param value
	 * @return
	 */
	public static boolean set(Context context, String name, boolean value) {
		final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		Editor editor = prefs.edit();
		editor.putBoolean(name, value);
		return editor.commit();	//提交
	}
}

/2013.08.14_ToggleButton_demo/src/com/wwj/toggle/DisplayUtils.java
package com.wwj.toggle;

import android.content.Context;

public class DisplayUtils {
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	public static int getScreenWidth(Context context) {
		return context.getResources().getDisplayMetrics().widthPixels;
	}

	public static int getScreenHeight(Context context) {
		return context.getResources().getDisplayMetrics().heightPixels;
	}
}


/2013.08.14_ToggleButton_demo/src/com/wwj/toggle/ToggleListener.java
package com.wwj.toggle;


import android.content.Context;
import android.view.Gravity;
import android.view.animation.TranslateAnimation;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.ToggleButton;

/**
 * 状态按钮的监听事件
 * 
 * @author wwj
 * 
 */
public class ToggleListener implements OnCheckedChangeListener {
	private Context context;
	private String settingName;
	private ToggleButton toggle;
	private ImageButton toggle_Button;

	public ToggleListener(Context context, String settingName,
			ToggleButton toggle, ImageButton toggle_Button) {
		this.context = context;
		this.settingName = settingName;
		this.toggle = toggle;
		this.toggle_Button = toggle_Button;
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		// 保存设置
		if ("自动播放".equals(settingName)) {
			SettingUtils.set(context, SettingUtils.AUTO_PLAY, isChecked);
		} else if ("开机自启动".equals(settingName)) {
			SettingUtils.set(context, SettingUtils.IS_AUTO_START, isChecked);
		}
		// 播放动画
		RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) toggle_Button
				.getLayoutParams();
		if (isChecked) {
			// 调整位置
			params.addRule(RelativeLayout.ALIGN_RIGHT, -1);
			if ("自动播放".equals(settingName)) {
				params.addRule(RelativeLayout.ALIGN_LEFT, R.id.toggle_AutoPlay);
			} else if ("开机自启动".equals(settingName)) {
				params.addRule(RelativeLayout.ALIGN_LEFT,
						R.id.toggle_StartOnBoot);
			}
			toggle_Button.setLayoutParams(params);
			toggle_Button.setImageResource(R.drawable.progress_thumb_selector);
			toggle.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
			// 播放动画
			TranslateAnimation animation = new TranslateAnimation(
					DisplayUtils.dip2px(context, 40), 0, 0, 0);
			animation.setDuration(200);
			toggle_Button.startAnimation(animation);
		} else {
			// 调整位置
			if ("自动播放".equals(settingName)) {
				params.addRule(RelativeLayout.ALIGN_RIGHT, R.id.toggle_AutoPlay);
			} else if ("开机自启动".equals(settingName)) {
				params.addRule(RelativeLayout.ALIGN_RIGHT,
						R.id.toggle_StartOnBoot);
			}
			params.addRule(RelativeLayout.ALIGN_LEFT, -1);
			toggle_Button.setLayoutParams(params);
			toggle_Button
					.setImageResource(R.drawable.progress_thumb_off_selector);

			toggle.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
			// 播放动画
			TranslateAnimation animation = new TranslateAnimation(
					DisplayUtils.dip2px(context, -40), 0, 0, 0);
			animation.setDuration(200);
			toggle_Button.startAnimation(animation);
		}
	}

}



  • 7
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论
ToggleButtonAndroid中的一个控件,它可以用来切换两种状态,通常用于表示开关按钮。在使用ToggleButton时,你可以通过设置几个常用属性来自定义按钮的行为和外观,如android:textOn和android:textOff属性可以设置按钮在不同状态下显示的文字。 如果你想在Android Studio中使用ToggleButton,你可以参考以下步骤: 1. 在布局文件中添加ToggleButton控件,设置它的id和其他属性,如android:textOn和android:textOff。 2. 在Activity中找到ToggleButton控件,使用findViewById方法绑定该控件。 3. 为ToggleButton设置一个监听器,通过setOnCheckedChangeListener方法实现。 4. 在监听器的onCheckedChanged方法中,根据按钮的状态进行相应的操作。 以下是一个简单的示例代码,演示了如何在Android Studio中创建和使用ToggleButton控件: ```java public class MainActivity extends AppCompatActivity { private TextView tv_show = null; private ToggleButton btn_tog_test = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv_show = findViewById(R.id.tv_show); btn_tog_test = findViewById(R.id.btn_tog_test); btn_tog_test.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { if (isChecked) { tv_show.setText("已经开始"); } else { tv_show.setText("已经停止"); } } }); } } ``` 在这个示例中,我们创建了一个Activity,并在布局文件中添加了一个TextView和一个ToggleButton控件。当ToggleButton的状态切换时,我们通过监听器来更新TextView的文本。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小巫技术博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值