Android自定義控件

出自:http://www.92coding.com/blog/index.php/archives/143.html


今天和大家分享下組合控件的使用。很多時候android自定義控件並不能滿足需求,如何做呢?很多方法,可以自己繪製一個,可以通過繼承基礎控件來重寫某些環節,當然也可以將控件組合成一個新控件,這也是最方便的一個方法。今天就來介紹下如何使用組合控件,將通過兩個實例來介紹。
第一個實現一個帶圖片和文字的按鈕,如圖所示:
<a href="http://blog.92coding.com/wp-content/uploads/2012/01/12.jpg" class="cboxElement" rel="example4" 143"="" style="text-decoration: initial; color: rgb(1, 150, 227);">若水工作室
整個過程可以分四步走。第一步,定義一個layout,實現按鈕內部的佈局。代碼如下:
custom_button.xml

1 <?xml version="1.0" encoding="utf-8"?> 
2 <LinearLayout xmlns:android=http://schemas.android.com/apk/res/android" 
3     android:orientation="horizontal" 
4     android:layout_width="fill_parent" 
5     android:layout_height="fill_parent"
6     
7  <ImageView 
8   android:id="@+id/iv" 
9      android:layout_width="wrap_content" 
10      android:layout_height="wrap_content" 
11      android:layout_gravity="center_vertical"
12      android:paddingLeft="10.0dip"
13      android:paddingTop="10.0dip"
14      android:paddingBottom="10.0dip"
15      /> 
16  <TextView 
17   android:id="@+id/tv" 
18      android:layout_width="wrap_content" 
19      android:layout_height="wrap_content" 
20      android:textColor="#ffffff" 
21      android:layout_marginLeft="8dip" 
22      android:layout_gravity="center_vertical" 
23      android:paddingLeft="5.0dip"
24      android:paddingTop="10.0dip"
25      android:paddingBottom="10.0dip"
26      android:paddingRight="10.0dip"
27      android:textSize="18.0sp"
28      /> 
29 </LinearLayout>

這個xml實現一個左圖右字的佈局,接下來寫一個類繼承LinearLayout,導入剛剛的佈局,並且設置需要的方法,從而使的能在代碼中控制這個自定義控件內容的顯示。代碼如下:
CustomButton.java

1 package com.szy.customview;
2  
3 import android.content.Context;
4 import android.util.AttributeSet;
5 import android.view.LayoutInflater;
6 import android.widget.ImageView;
7 import android.widget.LinearLayout;
8 import android.widget.TextView;
9  
10 /**
11  *@author coolszy
12  *@date 2011-12-20
14  */
15 public class CustomButton extends LinearLayout
16 {
17  
18  private ImageView iv;
19  private TextView tv;
20  
21  public CustomButton(Context context)
22  {
23   this(context, null);
24  }
25  
26  public CustomButton(Context context, AttributeSet attrs)
27  {
28   super(context, attrs);
29   // 導入佈局
30   LayoutInflater.from(context).inflate(R.layout.custom_button, this, true);
31   iv = (ImageView) findViewById(R.id.iv);
32   tv = (TextView) findViewById(R.id.tv);
33  }
34  
35  /**
36   * 設置圖片資源
37   */
38  public void setImageResource(int resId)
39  {
40   iv.setImageResource(resId);
41  }
42  
43  /**
44   * 設置顯示的文字
45   */
46  public void setTextViewText(String text)
47  {
48   tv.setText(text);
49  }
50 }

第三步,在需要使用這個自定義控件的layout中加入這控件,只需要在xml中加入即可。方法如下:
main.xml

1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
2  android:layout_width="fill_parent" 
3  android:layout_height="fill_parent" 
4  android:orientation="vertical" 
5  
6  <com.szy.customview.CustomButton
7      android:id="@+id/bt_confirm" 
8      android:layout_width="wrap_content"
9      android:layout_height="wrap_content" 
10      android:background="@drawable/button_bg" 
11      /> 
12  <com.szy.customview.CustomButton
13      android:id="@+id/bt_cancel" 
14      android:layout_width="wrap_content"
15      android:layout_height="wrap_content" 
16      android:background="@drawable/button_bg" 
17     /> 
18 </LinearLayout>

注意的是,控件標籤使用完整的類名即可。爲了給按鈕一個點擊效果,你需要給他一個selector背景,這裏就不說了。
最後一步,即在activity中設置該控件的內容。當然,在xml中也可以設置,但是隻能設置一個,當我們需要兩次使用這樣的控件,並且顯示內容不同時就不行了。在activity中設置也非常簡單,我們在CustomButton這個類中已經寫好了相應的方法,簡單調用即可。代碼如下:

1 package com.szy.customview;
2  
3 import android.app.Activity;
4 import android.os.Bundle;
5 import android.view.View;
6 import android.view.View.OnClickListener;
7  
8 public class MainActivity extends Activity
9 {
10  private CustomButton btnConfirm;
11  private CustomButton btnCancel;
12  
13  @Override
14  public void onCreate(Bundle savedInstanceState)
15  {
16   super.onCreate(savedInstanceState);
17   setContentView(R.layout.main);
18   btnConfirm = (CustomButton) findViewById(R.id.bt_confirm);
19   btnCancel = (CustomButton) findViewById(R.id.bt_cancel);
20  
21   btnConfirm.setTextViewText("確定");
22   btnConfirm.setImageResource(R.drawable.confirm);
23   btnCancel.setTextViewText("取消");
24   btnCancel.setImageResource(R.drawable.cancel);
25  
26   btnConfirm.setOnClickListener(new OnClickListener()
27   {
28    @Override
29    public void onClick(View v)
30    {
31     // 在這裏可以實現點擊事件
32    }
33   });
34  }
35 }

這樣,一個帶文字和圖片的組合按鈕控件就完成了。這樣梳理一下,使用還是非常簡單的。組合控件能做的事還非常多,主要是在類似上例中的CustomButton類中寫好要使用的方法即可。
再來看一個組合控件,帶刪除按鈕的EidtText。即在用戶輸入後,會出現刪除按鈕,點擊即可取消用戶輸入。
定義方法和上例一樣。首先寫一個自定義控件的佈局:
custom_editview.xml

1 <?xml version="1.0" encoding="utf-8"?> 
2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
3     android:layout_width="fill_parent" 
4     android:layout_height="fill_parent" 
5     
6  <EditText 
7      android:id="@+id/et" 
8      android:layout_width="fill_parent" 
9      android:layout_height="wrap_content" 
10      android:singleLine="true" 
11      /> 
12  <ImageButton 
13      android:id="@+id/ib" 
14      android:visibility="gone" 
15      android:src="@drawable/cancel" 
16      android:layout_width="wrap_content" 
17      android:layout_height="wrap_content" 
18      android:background="#00000000" 
19      android:layout_alignRight="@+id/et" /> 
20 </RelativeLayout>

實現輸入框右側帶按鈕效果,注意將按鈕隱藏。然後寫一個CustomEditView類,實現刪除用戶輸入功能。這裏用到了TextWatch這個接口,監聽輸入框中的文字變化。使用也很簡單,實現他的三個方法即可。看代碼:
CustomEditView.java

1 package com.szy.customview;
2  
3 import android.content.Context;
4 import android.text.Editable;
5 import android.text.TextWatcher;
6 import android.util.AttributeSet;
7 import android.view.LayoutInflater;
8 import android.view.View;
9 import android.widget.EditText;
10 import android.widget.ImageButton;
11 import android.widget.LinearLayout;
12  
13 /**
14  *@author coolszy
15  *@date 2011-12-20
17  */
18 public class CustomEditView extends LinearLayout implements EdtInterface
19 {
20  ImageButton ib;
21  EditText et;
22  
23  public CustomEditView(Context context)
24  {
25   super(context);
26  
27  }
28  public CustomEditView(Context context, AttributeSet attrs)
29  {
30   super(context, attrs);
31   LayoutInflater.from(context).inflate(R.layout.custom_editview, this, true);
32   init();
33  
34  }
35  private void init()
36  {
37   ib = (ImageButton) findViewById(R.id.ib);
38   et = (EditText) findViewById(R.id.et);
39   et.addTextChangedListener(tw);// 爲輸入框綁定一個監聽文字變化的監聽器
40   // 添加按鈕點擊事件
41   ib.setOnClickListener(new OnClickListener()
42   {
43    @Override
44    public void onClick(View v)
45    {
46     hideBtn();// 隱藏按鈕
47     et.setText("");// 設置輸入框內容爲空
48    }
49   });
50  
51  }
52  // 當輸入框狀態改變時,會調用相應的方法
53  TextWatcher tw = new TextWatcher()
54  {
55    
56   @Override
57   public void onTextChanged(CharSequence s, int start, int before, int count)
58   {
59    // TODO Auto-generated method stub
60  
61   }
62    
63   @Override
64   public void beforeTextChanged(CharSequence s, int start, int count, int after)
65   {
66    // TODO Auto-generated method stub
67  
68   }
69    
70   // 在文字改變後調用
71   @Override
72   public void afterTextChanged(Editable s)
73   {
74    if (s.length() == 0)
75    {
76     hideBtn();// 隱藏按鈕
77    } else
78    {
79     showBtn();// 顯示按鈕
80    }
81   }
82  };
83  
84  @Override
85  public void hideBtn()
86  {
87   // 設置按鈕不可見
88   if (ib.isShown())
89    ib.setVisibility(View.GONE);
90  
91  }
92  
93  @Override
94  public void showBtn()
95  {
96   // 設置按鈕可見
97   if (!ib.isShown())
98   {
99    ib.setVisibility(View.VISIBLE);
100   }
101  }
102 }
103  
104 interface EdtInterface
105 {
106  public void hideBtn();
107  public void showBtn();
108 }

在TextWatch接口的afterTextChanged方法中對文字進行判斷,若長度爲0,就隱藏按鈕,否則,顯示按鈕。
另外,實現ImageButton(即那個叉)的點擊事件,刪除輸入框中的內容,並隱藏按鈕。
後面兩步的實現就是加入到實際佈局中:
main.xml

1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
2  android:layout_width="fill_parent" 
3  android:layout_height="fill_parent" 
4  android:orientation="vertical" 
5  >
6  <com.szy.customview.CustomEditView
7   android:layout_width="fill_parent"
8      android:layout_height="wrap_content" 
9     />
10 </LinearLayout
11   

最後顯示效果如圖:
<a href="http://blog.92coding.com/wp-content/uploads/2012/01/21.jpg" class="cboxElement" rel="example4" 143"="" style="text-decoration: initial; color: rgb(1, 150, 227);">若水工作室

源碼下載地址:http://115.com/file/aq5qvh67


發佈了31 篇原創文章 · 獲贊 3 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章