先看效果图:
第一步:
在valuses下面自定义目录:
第二步:
自定义ImageView
package com.jiaruihuademo.myattrimageview;
import java.util.Timer;
import java.util.TimerTask;
import com.jiaruihuademo.myattrimageview.R;
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 perAlpha = 0;
//当前图像的透明度
private int curAlpha = 0;
//每隔多长时间改变一次透明度
private int SPEED = 300;
public AlphaImageView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
//找到自定义的属性
TypedArray typedArray = context.obtainStyledAttributes(attrs,
R.styleable.AlphaImageView);
//获取duration参数
int duration = typedArray.getInt(R.styleable.AlphaImageView_duration, 0);
//计算透明度改变的大小
perAlpha = 255*SPEED/duration;
}
Handler handler = new Handler(){
public void handleMessage(Message msg) {
if (msg.what==0x123) {
curAlpha +=perAlpha;
if (curAlpha>255) {
curAlpha=255;
}
AlphaImageView.this.setAlpha(curAlpha);
}
};
};
@Override
protected void onDraw(Canvas canvas) {
this.setAlpha(curAlpha);
super.onDraw(canvas);
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
Message msg = new Message();
msg.what=0x123;
if (curAlpha>255) {
timer.cancel();
}else {
handler.sendMessage(msg);
}
}
}, 0,SPEED);
}
}
第三步:
在layout布局下:
xmlns:jiaruihuademo="http://schemas.android.com/apk/res/com.jiaruihuademo.myattrimageview"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
android:id="@+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:src="@drawable/t01397599f43ebc8f8c"
jiaruihuademo:duration="60000"/>
源码下载