原文地址:http://happyrxk.cn/?post=19
下面我们介绍android自定义控件的实现,简单说就是指自己继承原有控件并增加一些方法和属性
首先我们需要在资源文件里定义所需的属性
在res/values下新建attr.xml
内容如下
<?xml version="1.0" encoding="utf-8"?> <resources> <attr name="duration" fromat="integer"> </attr> <declare-styleable name="AlphaImageView"> <attr name="duration"/> </declare-styleable> </resources>
然后我们定义一个AlphaImageView类,继承ImageView
package com.happyrxk.my; import java.util.Timer; import java.util.TimerTask; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.widget.ImageView; public class AlphaImageView extends ImageView{ private int alphaDelta = 0; private int curAlpha = 0; private final int SPEED = 300; private final int CHANGE = 0x110; Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); if(msg.what==CHANGE){ curAlpha+=alphaDelta; if(curAlpha>255){ curAlpha = 255; } AlphaImageView.this.setAlpha(curAlpha); } } }; public AlphaImageView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AlphaImageView); int duration = typedArray.getInt(R.styleable.AlphaImageView_duration, 0); alphaDelta = 255 * SPEED /duration; // TODO Auto-generated constructor stub } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); this.setAlpha(curAlpha); final Timer timer = new Timer(); timer.schedule(new TimerTask(){ @Override public void run() { // TODO Auto-generated method stub Message msg = new Message(); msg.what = CHANGE; if(curAlpha>=255){ timer.cancel(); }else{ handler.sendMessage(msg); } } }, 0, SPEED); } }
在我们在xml中用自定义控件是的方法如下
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:happyrxk="http://schemas.android.com/apk/res/com.happyrxk.my" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <com.happyrxk.my.AlphaImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" happyrxk:duration="60000"/> </RelativeLayout>