今天练习中遇到一个让我记起头疼的问题,以前倒是写过自定义组件,但是使用属性资源中的自定义的还是头次碰到
首先定义一个带duration的资源attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- 定义一个属性 -->
<attr name="duration"></attr>
<!-- 定义一个styleable对象来组合多个属性 -->
<declare-styleable name="AlphaImageView">
<attr name="duration" />
</declare-styleable>
</resources>
然后写一个图片透明度变换的自定义组件AlphaImageView:
package com.cbg.alphaimage;
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;
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 0x123) {
// 每次增加curAlpha的值
curAlpha += alphaDelta;
if (curAlpha > 255)
curAlpha = 255;
// 修改该ImageView的透明度
AlphaImageView.this.setAlpha(curAlpha);
}
}
};
public AlphaImageView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray = context.obtainStyledAttributes(attrs,
R.styleable.AlphaImageView);
// 获取duration参数
int duration = typedArray
.getInt(R.styleable.AlphaImageView_duration, 0);
// 计算图像透明度每次改变的大小
alphaDelta = 255 * SPEED / duration;
}
@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() {
Message msg = new Message();
msg.what = 0x123;
if (curAlpha >= 255) {
timer.cancel();
} else {
handler.sendMessage(msg);
}
}
}, 0, SPEED);
}
}
再在main.xml文件中加入自定义组件AlphaImageView以及资源属性duration:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cbg="http://schemas.android.com/apk/res/com.cbg.alphaimage"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- 使用自定义组件,并指定属性资源中定义的属性 -->
<com.cbg.alphaimage.AlphaImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/ee"
cbg:duration="60000" />
</LinearLayout>
最后将main设置为MainActivity的布局即可。
注意:
其中xmlns:cbg="http://schemas.android.com/apk/res/com.cbg.alphaimage"中的<pre name="code" class="java">com.cbg.alphaimage为AlphaImageView的包名。