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

本文介绍如何通过自定义View组件创建带有动画效果的图片显示功能,并详细解释了属性定义及在布局文件中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用场合:当用户使用自定义的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/ + 包名

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    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" />

</RelativeLayout>


代码部分没有改变。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值