返回

Android 使用自定义组件和自定义属性

发布时间:2022-11-10 08:51:57 356
# webkit# android

使用场合:当用户使用自定义的View组件时,需要指定属性。例如要实现一个默认的带动画效果的图片,图片显示时自动从全透明变成完全不透明(需要添加一个持续的事件)。

存放位置:/res/values/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>

定义这样一个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) {
switch (msg.what) {
case 0x11:
CurAlpha += alphaDelta;
if (CurAlpha >= 255)
CurAlpha = 255;
// 修改透明度
AlphaImageView.this.setAlpha(CurAlpha);
break;

default:
break;
}
}

};

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);
// 计算图像每次改变的大小
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() {
// TODO Auto-generated method stub
Message msg = Message.obtain();
msg.what = 0x11;
if (CurAlpha >= 255) {
timer.cancel();
} else {
handler.sendMessage(msg);
}
}
}, 0, SPEED);
}
}

在布局文件中使用该View并设置属性

引入资源的方法是​​http://schemas.android.com/apk/res/​​ + 包名

    xmlns:tools="http://schemas.android.com/tools"
xmlns:crazyit="http://schemas.android.com/apk/res/com.attributexmldemo"
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.attributexmldemo.AlphaImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/icon1"
crazyit:duration="60000" />

 

代码部分没有改变。

 

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线
下一篇
Android Bitmap 2022-11-10 08:13:38