android 自定义view

自定义view:
1. 继承view,重构构造方法:
 public ImageAlternateButton(Context context, AttributeSet attrs)
 {
  super(context, attrs);

  // 赋值设置监听
  TypedArray a = context.obtainStyledAttributes(attrs,
    R.styleable.iaButton, 0, 0);
  int temp1 = a.getResourceId(R.styleable.iaButton_downDrawable, 0);
  int temp2 = a.getResourceId(R.styleable.iaButton_upDrawable, 0); //此处遵循规则attrs中定义的declare-styleable name “_” attr name
  a.recycle();

  // 设置按下及弹起时的图片资源
  this.upDrawable = context.getResources().getDrawable(temp2);
  this.downDrawable = context.getResources().getDrawable(temp1);
  this.setImageDrawable(upDrawable);
  this.setOnTouchListener(this);
 }
2.  如果自定义的View需要有自定义的属性,需要在values下建立attrs.xml。在其中定义你的属性
如:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="iaButton">
        <attr name="upDrawable" format="reference|color"  />
        <attr name="downDrawable" format="reference|color"  />
    </declare-styleable>
</resources>
3. 在使用到自定义View的xml布局文件中需要加入xmlns:前缀="http://schemas.android.com/apk/res/你的自定义View所在的包路径".
    在使用自定义属性的时候,使用前缀:属性名,如my:textColor="#FFFFFFF"。
  <com.view.ImageAlternateButton
    android:id="@+id/chat_message_repeat_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:visibility="gone" 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:iaButton="http://schemas.android.com/apk/res/com.hotalk"  
    iaButton:upDrawable="@drawable/ico_0821"
    iaButton:downDrawable="@drawable/ico_0821"
     /> 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值