先看效果圖:
第一步:
在valuses下面自定義目錄:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- 定義一個屬性 -->
<attr name="duration"></attr>
<!-- 定義一個styleable對象來組合多個屬性 -->
<declare-styleable name="AlphaImageView">
<attr name="duration"/>
</declare-styleable>
</resources>
第二步:
自定義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"定義,看清楚 -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
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" >
<com.jiaruihuademo.myattrimageview.AlphaImageView
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"/>
</RelativeLayout>