码迷,mamicode.com
首页 > 移动开发 > 详细

一个简单的android自定义view(Switch Button for api < 14)

时间:2014-11-27 16:32:55      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:android   style   http   io   ar   color   sp   java   for   

1.编写主类

package com.sample.button;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.CompoundButton;

import com.example.buttonsample.R;

public class MyButton extends CompoundButton {

	public MyButton(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	private Drawable imgOFF;
	private Drawable imgON;

	public MyButton(Context context, AttributeSet attrs) {
		super(context, attrs);
		TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyButton, 0, 0);
		try {
			imgOFF = a.getDrawable(R.styleable.MyButton_imgOFF);
			imgON = a.getDrawable(R.styleable.MyButton_imgON);
		} catch (Exception e) {
			e.printStackTrace();
		}
		a.recycle();
	}

	public MyButton(Context context) {
		super(context);
	}

	@Override
	public void setChecked(boolean checked) {
		super.setChecked(checked);
		udpateDrawable();

	}

	private void udpateDrawable() {
		if (this.isChecked()) {
			Log.e(MyButton.class.getName(),"changing to imgON");
			this.setBackgroundDrawable(imgON);
		} else {
			Log.e(MyButton.class.getName(),"changing to imgOFF");
			this.setBackgroundDrawable(imgOFF);
		}
	}

	@Override
	protected void onFinishInflate() {
		udpateDrawable();
		super.onFinishInflate();
	}

}



2.编写attrs定义文件(res/values/attrs.xml)

<?xml version="1.0" encoding="utf-8"?>
<resources> 
    <declare-styleable name="MyButton">
        <attr name="imgON" format="reference" />
        <attr name="imgOFF" format="reference" />
    </declare-styleable> 
</resources>



3.涉及到的2个图片资源如下

res/drawable/off.png

res/drawable/on.png

4.测试用activity的layout文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res/com.example.buttonsample"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <com.sample.button.MyButton
        android:id="@+id/testmy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/white"
        app:imgOFF="@drawable/off"
        app:imgON="@drawable/on" >
    </com.sample.button.MyButton>

</LinearLayout>


5.实际效果即:

点击按钮时,按钮会在以下2个图片之间切换.

一个简单的android自定义view(Switch Button for api < 14)

标签:android   style   http   io   ar   color   sp   java   for   

原文地址:http://my.oschina.net/u/560844/blog/349395

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!