Android中自定義控件,三個構造函數


自定義控件時,最好抽象得徹底,並且編寫需嚴謹,因為可能程序中多處都會引用到它,或者提供給團隊中的其他人使用。  

其一般步驟為:

1.創建控件的類文件,定義其功能邏輯。一般繼承自現有控件或者View   

2.在res/values目錄下創建attrs.xml文件,用於定義該控件的xml標簽屬性,方便在使用xml聲明該控件時設置參數    

3.實現該控件的構造器,在構造器中把xml標簽屬性與后台代碼中的變量相連接   

4.完成以上步驟之后,便可使用該控件  


需要注意的地方:  

一.View的三個構造函數       

第一個構造函數:     當不需要使用xml聲明或者不需要使用inflate動態加載時候,實現此構造函數即可  

第二個構造函數:     當需要在xml中聲明此控件,則需要實現此構造函數。並且在構造函數中把自定義的屬性與控件的數據成員連接起來。  

第三個構造函數:     接受一個style資源  

二.View重要的回調  

  

onFinishInflate()     在此控件被通過xml聲明的方式創建之后調用  

onMeasure(in,int)     計算本控件的寬高,如果繼承自原有控件,則一般不需要重寫此方法  

onLayout()     用於布局控件,對於不是繼承ViewGroup的控件,一般不需要重寫此方法  

onDraw()     在繪制控件時候調用,控件具體長什么樣子就在此方法中實現  

三.設置自定義屬性  

使用自定義控件時候,需要通過把xml中聲明的屬性與控件的數據成員連接起來  

在res/values目錄下創建attrs.xml文件  

定義屬性組  

在構造函數中獲取這些值  


Example:  

1.myButton.java  

      
public class myButton extends Button {  private int step;   public myButton(Context context, AttributeSet attrs, int defStyle)  {   super(context, attrs, defStyle);   // TODO Auto-generated constructor stub   init(attrs);  }  public myButton(Context context, AttributeSet attrs)  {   super(context, attrs);   // TODO Auto-generated constructor stub   init(attrs);  }  public myButton(Context context)  {   super(context);   // TODO Auto-generated constructor stub  }   private void init(AttributeSet attrs)  {   if (attrs != null)   {    TypedArray a = getContext().obtainStyledAttributes(attrs,      R.styleable.myButton);       step = a.getInt(R.styleable.myButton_step, 0);       a.recycle();       this.setText(step+"");   }  } }
myButton.java  

2.attrs.xml

      
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="myButton"> <attr name="step" format="integer"/> </declare-styleable> </resources>
attrs.xml  

3.使用自定義控件

xmlns:views="http://schemas.android.com/apk/res/" + 子包名

      
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  xmlns:tools="http://schemas.android.com/tools"  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"  android:orientation="vertical"  tools:context=".MainActivity"   xmlns:views="http://schemas.android.com/apk/res/com.example.createvewtest">  <TextView   android:layout_width="wrap_content"   android:layout_height="wrap_content"   android:text="@string/hello_world" />   <com.example.views.myButton   android:id="@+id/btn"   android:text="button"   views:step="10"   android:layout_width="match_parent"   android:layout_height="wrap_content"/> </LinearLayout>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM