---
title: "android 自定义view"
author: "ThinkGoogle"
date: "2012-04-07T15:54:42Z"
tags: []
categories: ["移动开发"]
slug: "android-view"
draft: false
lastmod: "2012-04-07T15:54:42Z"
id: 1478059
url: "https://thinkgoogle.iteye.com/blog/1478059"
---

自定义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。在其中定义你的属性  
如：  
&lt;?xml version="1.0" encoding="utf-8"?&gt;  
&lt;resources&gt;  
    &lt;declare-styleable name="iaButton"&gt;  
        &lt;attr name="upDrawable" format="reference|color"  /&gt;  
        &lt;attr name="downDrawable" format="reference|color"  /&gt;  
    &lt;/declare-styleable&gt;  
&lt;/resources&gt;  
3\. 在使用到自定义View的xml布局文件中需要加入xmlns:前缀="[http://schemas.android.com/apk/res/](http://schemas.android.com/apk/res/)你的自定义View所在的包路径".  
    在使用自定义属性的时候，使用前缀：属性名，如my:textColor="#FFFFFFF"。  
  &lt;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](http://schemas.android.com/apk/res/android)"  
    xmlns:iaButton="[http://schemas.android.com/apk/res/com.hotalk](http://schemas.android.com/apk/res/com.hotalk)"    
    iaButton:upDrawable="@drawable/ico\_0821"  
    iaButton:downDrawable="@drawable/ico\_0821"  
     /&gt;