androidの自定义view属性资源

androidの自定义view属性资源
1. 添加自定义View的属性文件
在res/values中新建attrs.xml文件(文件名可另取,不过推荐用attrs.xml,可以将自定义属性都放入其中),内容为
属性资源文件的根元素也是 <resources.../>,该元素包含两个子元素:
   attr 子元素:定义一个属性。
   declare-styleable 子元素:定义一个styleable对象,每个styleable对象就是一组attr属性的集合。
<?xml version="1.0" encoding="utf-8"?>
<resources>
	<!-- 定义一个属性 -->
	<attr name="duration">
	</attr>
	<!-- 定义一个styleable对象来组合多个属性 -->
	<declare-styleable name="AlphaImageView">
		<attr name="duration"/>
	</declare-styleable>
</resources>
这里定义的属性 duration, 对应布局文件中使用的属性:crazyit:duration, 在这里可以指定值:
<attr name="duration" format="integer"/>
同时,上面定义的 AlphaImageView, 随意命名的,但是对应Java代码中AttributeSet对象获取的属性。
然后看下布局文件代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:crazyit="http://schemas.android.com/apk/res/org.crazyit.res"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <!-- 使用自定义组件,并指定属性资源中定义的属性 -->
    <org.crazyit.res.AlphaImageView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/ee"
        crazyit:duration="60000" />

</LinearLayout>
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);
	}
}
注意到:获取了定义的 AlphaImageView 时定义的duration属性,并根据该属性计算图片的透明度的变化幅度,接着重写OnDraw(),启动来控制图片的变化。

2. 代码下载地址
    源代码

   更多自定义view 代码

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值