自定义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"
/>