如何在Android應(yīng)用中自定義一個(gè)控件-創(chuàng)新互聯(lián)

本篇文章為大家展示了如何在Android應(yīng)用中自定義一個(gè)控件,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。

目前創(chuàng)新互聯(lián)已為超過千家的企業(yè)提供了網(wǎng)站建設(shè)、域名、網(wǎng)絡(luò)空間、網(wǎng)站托管、服務(wù)器租用、企業(yè)網(wǎng)站設(shè)計(jì)、澄江網(wǎng)站維護(hù)等服務(wù),公司將堅(jiān)持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長,共同發(fā)展。

開發(fā)自定義控件的步驟:

1、了解View的工作原理
2、 編寫繼承自View的子類
3、 為自定義View類增加屬性
4、 繪制控件
5、 響應(yīng)用戶消息
6 、自定義回調(diào)函數(shù)  

一、View結(jié)構(gòu)原理

Android系統(tǒng)的視圖結(jié)構(gòu)的設(shè)計(jì)也采用了組合模式,即View作為所有圖形的基類,Viewgroup對View繼承擴(kuò)展為視圖容器類。
View定義了繪圖的基本操作
基本操作由三個(gè)函數(shù)完成:measure()、layout()、draw(),其內(nèi)部又分別包含了onMeasure()、onLayout()、onDraw()三個(gè)子方法。具體操作如下:

1、measure操作

     measure操作主要用于計(jì)算視圖的大小,即視圖的寬度和長度。在view中定義為final類型,要求子類不能修改。measure()函數(shù)中又會(huì)調(diào)用下面的函數(shù):

     (1)onMeasure(),視圖大小的將在這里最終確定,也就是說measure只是對onMeasure的一個(gè)包裝,子類可以覆寫onMeasure()方法實(shí)現(xiàn)自己的計(jì)算視圖大小的方式,并通過setMeasuredDimension(width, height)保存計(jì)算結(jié)果。 

2、layout操作

     layout操作用于設(shè)置視圖在屏幕中顯示的位置。在view中定義為final類型,要求子類不能修改。layout()函數(shù)中有兩個(gè)基本操作:

     (1)setFrame(l,t,r,b),l,t,r,b即子視圖在父視圖中的具體位置,該函數(shù)用于將這些參數(shù)保存起來;
     (2)onLayout(),在View中這個(gè)函數(shù)什么都不會(huì)做,提供該函數(shù)主要是為viewGroup類型布局子視圖用的; 

3、draw操作

     draw操作利用前兩部得到的參數(shù),將視圖顯示在屏幕上,到這里也就完成了整個(gè)的視圖繪制工作。子類也不應(yīng)該修改該方法,因?yàn)槠鋬?nèi)部定義了繪圖的基本操作:

     (1)繪制背景;
     (2)如果要視圖顯示漸變框,這里會(huì)做一些準(zhǔn)備工作;
     (3)繪制視圖本身,即調(diào)用onDraw()函數(shù)。在view中onDraw()是個(gè)空函數(shù),也就是說具體的視圖都要覆寫該函數(shù)來實(shí)現(xiàn)自己的顯示(比如TextView在這里實(shí)現(xiàn)了繪制文字的過程)。而對于ViewGroup則不需要實(shí)現(xiàn)該函數(shù),因?yàn)樽鳛槿萜魇恰皼]有內(nèi)容“的,其包含了多個(gè)子view,而子View已經(jīng)實(shí)現(xiàn)了自己的繪制方法,因此只需要告訴子view繪制自己就可以了,也就是下面的dispatchDraw()方法;
     (4)繪制子視圖,即dispatchDraw()函數(shù)。在view中這是個(gè)空函數(shù),具體的視圖不需要實(shí)現(xiàn)該方法,它是專門為容器類準(zhǔn)備的,也就是容器類必須實(shí)現(xiàn)該方法;
     (5)如果需要(應(yīng)用程序調(diào)用了setVerticalFadingEdge或者setHorizontalFadingEdge),開始繪制漸變框;
     (6)繪制滾動(dòng)條;
      從上面可以看出自定義View需要最少覆寫onMeasure()和onDraw()兩個(gè)方法。 

二、View類的構(gòu)造方法

創(chuàng)建自定義控件的3種主要實(shí)現(xiàn)方式:

1)繼承已有的控件來實(shí)現(xiàn)自定義控件: 主要是當(dāng)要實(shí)現(xiàn)的控件和已有的控件在很多方面比較類似, 通過對已有控件的擴(kuò)展來滿足要求。

2)通過繼承一個(gè)布局文件實(shí)現(xiàn)自定義控件,一般來說做組合控件時(shí)可以通過這個(gè)方式來實(shí)現(xiàn)。

    注意此時(shí)不用onDraw方法,在構(gòu)造廣告中通過inflater加載自定義控件的布局文件,再addView(view),自定義控件的圖形界面就加載進(jìn)來了。

3)通過繼承view類來實(shí)現(xiàn)自定義控件,使用GDI繪制出組件界面,一般無法通過上述兩種方式來實(shí)現(xiàn)時(shí)用該方式。 

三、自定義View增加屬性的兩種方法:

1)在View類中定義。通過構(gòu)造函數(shù)中引入的AttributeSet 去查找XML布局的屬性名稱,然后找到它對應(yīng)引用的資源ID去找值。
案例:實(shí)現(xiàn)一個(gè)帶文字的圖片(圖片、文字是onDraw方法重繪實(shí)現(xiàn))

public class MyView extends View {
  
  private String mtext;
  private int msrc;

  public MyView(Context context) {
    super(context);
  }

  public MyView(Context context, AttributeSet attrs) {
    super(context, attrs);
    int resourceId = 0;
    int textId = attrs.getAttributeResourceValue(null, "Text",0);
    int srcId = attrs.getAttributeResourceValue(null, "Src", 0);
    mtext = context.getResources().getText(textId).toString();
    msrc = srcId;
  }
  
  @Override
  protected void onDraw(Canvas canvas) {
    Paint paint = new Paint();
    paint.setColor(Color.RED);
    InputStream is = getResources().openRawResource(msrc); 
        Bitmap mBitmap = BitmapFactory.decodeStream(is);
        int bh = mBitmap.getHeight();
        int bw = mBitmap.getWidth();
      canvas.drawBitmap(mBitmap, 0,0, paint);
    //canvas.drawCircle(40, 90, 15, paint);
    canvas.drawText(mtext, bw/2, 30, paint);
  }
}

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical" >

  <com.example.myimageview2.MyView
    android:id="@+id/myView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    Text="@string/hello_world"
    Src="@drawable/xh"/>

</LinearLayout>

屬性Text, Src在自定義View類的構(gòu)造方法中讀取。

2)通過XML為View注冊屬性。與Android提供的標(biāo)準(zhǔn)屬性寫法一樣。

案例:  實(shí)現(xiàn)一個(gè)帶文字說明的ImageView (ImageView+TextView組合,文字說明,可在布局文件中設(shè)置位置)

public class MyImageView extends LinearLayout {

  public MyImageView(Context context) {
    super(context);
  }

  public MyImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
    int resourceId = -1;
    TypedArray typedArray = context.obtainStyledAttributes(attrs,
        R.styleable.MyImageView);
    ImageView iv = new ImageView(context);
    TextView tv = new TextView(context);
    int N = typedArray.getIndexCount();
    for (int i = 0; i < N; i++) {
      int attr = typedArray.getIndex(i);
      switch (attr) {
      case R.styleable.MyImageView_Oriental:
        resourceId = typedArray.getInt(
            R.styleable.MyImageView_Oriental, 0);
        this.setOrientation(resourceId == 1 ? LinearLayout.HORIZONTAL
            : LinearLayout.VERTICAL);
        break;
      case R.styleable.MyImageView_Text:
        resourceId = typedArray.getResourceId(
            R.styleable.MyImageView_Text, 0);
        tv.setText(resourceId > 0 ? typedArray.getResources().getText(
            resourceId) : typedArray
            .getString(R.styleable.MyImageView_Text));
        break;
      case R.styleable.MyImageView_Src:
        resourceId = typedArray.getResourceId(
            R.styleable.MyImageView_Src, 0);
        iv.setImageResource(resourceId > 0 ?resourceId:R.drawable.ic_launcher);
        break;  
      }
    }
    addView(iv);
    addView(tv);
    typedArray.recycle();
  }
}

attrs.xml進(jìn)行屬性聲明, 文件放在values目錄下

<?xml version="1.0" encoding="utf-8"?>
<resources>

  <declare-styleable name="MyImageView">
    <attr name="Text" format="reference|string"></attr>
    <attr name="Oriental" >
      <enum name="Horizontal" value="1"></enum>
      <enum name="Vertical" value="0"></enum>
    </attr>
    <attr name="Src" format="reference|integer"></attr>
  </declare-styleable>

</resources>

MainActivity的布局文件:先定義命名空間 xmlns:uview="http://schemas.android.com/apk/res/com.example.myimageview2" (com.example.myimageview2為你
在manifest中定義的包名)

然后可以像使用系統(tǒng)的屬性一樣使用:uview:Oriental="Vertical"

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:uview="http://schemas.android.com/apk/res/com.example.myimageview2"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  tools:context=".MainActivity" >

  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

  <com.example.myimageview2.MyImageView
    android:id="@+id/myImageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    uview:Text="這是一個(gè)圖片說明" 
    uview:Src="@drawable/tw"
    uview:Oriental="Vertical">
  </com.example.myimageview2.MyImageView>

</LinearLayout>

四、控件繪制 onDraw() 

五、:自定義View的方法

onFinishInflate() 回調(diào)方法,當(dāng)應(yīng)用從XML加載該組件并用它構(gòu)建界面之后調(diào)用的方法
onMeasure() 檢測View組件及其子組件的大小
onLayout() 當(dāng)該組件需要分配其子組件的位置、大小時(shí)
onSizeChange() 當(dāng)該組件的大小被改變時(shí)
onDraw() 當(dāng)組件將要繪制它的內(nèi)容時(shí)
onKeyDown 當(dāng)按下某個(gè)鍵盤時(shí)
onKeyUp 當(dāng)松開某個(gè)鍵盤時(shí)
onTrackballEvent 當(dāng)發(fā)生軌跡球事件時(shí)
onTouchEvent 當(dāng)發(fā)生觸屏事件時(shí)
onWindowFocusChanged(boolean) 當(dāng)該組件得到、失去焦點(diǎn)時(shí)
onAtrrachedToWindow() 當(dāng)把該組件放入到某個(gè)窗口時(shí)
onDetachedFromWindow() 當(dāng)把該組件從某個(gè)窗口上分離時(shí)觸發(fā)的方法
onWindowVisibilityChanged(int): 當(dāng)包含該組件的窗口的可見性發(fā)生改變時(shí)觸發(fā)的方法

上述內(nèi)容就是如何在Android應(yīng)用中自定義一個(gè)控件,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

網(wǎng)頁標(biāo)題:如何在Android應(yīng)用中自定義一個(gè)控件-創(chuàng)新互聯(lián)
當(dāng)前URL:http://muchs.cn/article14/ddddde.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站內(nèi)鏈、ChatGPT、軟件開發(fā)、網(wǎng)站設(shè)計(jì)、網(wǎng)站排名網(wǎng)站維護(hù)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

微信小程序開發(fā)