Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 中 View 自定義組合控件的基本編寫方法

編輯:關於 Android 程式設計

很多時候,只要把 Android 提供的原生控件巧妙布局組合,就能得到一個全新的複用控件,這就是「自定義組合控件」。

那麼它在什麼場景下用得上呢?做項目時常會遇到某些布局被反復復制粘貼多次,不僅代碼結構混亂、代碼量激增,每個控件還要在 Java 裡聲明並處理邏輯,工作量著實可觀。這時就需要找到一種合理的「偷懶」方式來簡化這些重複勞動。下面以一張簡單的列表項布局為例來實現:

分析可知,這個布局裡沒有任何「全新」控件,全是系統原生控件。單條目的布局代碼如下:

 <!--?xml version=1.0 encoding=utf-8?--> <relativelayout android:background="@drawable/selector_blue" android:id="@+id/rl_show_address" android:layout_height="60dip" android:layout_width="match_parent" xmlns:android="https://schemas.android.com/apk/res/android"> <textview android:id="@+id/tv_title" android:layout_height="wrap_content" android:layout_marginleft="5dip" android:layout_margintop="1dip" android:layout_width="wrap_content" android:text="這是標題" android:textcolor="#000000" android:textsize="20sp"> <textview android:id="@+id/tv_desc" android:layout_below="@id/tv_title" android:layout_height="wrap_content" android:layout_marginleft="6dip" android:layout_margintop="1dip" android:layout_width="wrap_content" android:text="這是描述內容" android:textcolor="#99ff0000" android:textsize="14sp"> <checkbox android:clickable="false" android:focusable="false" android:id="@+id/cb_status" android:layout_alignparentright="true" android:layout_centervertical="true" android:layout_height="wrap_content" android:layout_width="wrap_content"> <!-- 加一條分割線 --> <view android:background="#000000/" android:layout_alignbottom="@id/cb_status" android:layout_alignparentbottom="true" android:layout_height="0.2dip" android:layout_margintop="7dip" android:layout_width="match_parent"> </view></checkbox></textview></textview></relativelayout>

這種布局確實簡單。但若產品經理說要在同一界面再加幾個、甚至十幾個這樣的條目,反復 Ctrl+C、Ctrl+V 顯然不是長久之計,後續增刪更會讓人崩潰。

仔細分析不難發現:每個子條目布局完全相同,唯一變化的是紅色 TextView 的文本,且它隨 CheckBox 的狀態改變。這種變化完全可以抽取到方法中——把子條目布局一次性封裝進一個 Java 類,每次使用時事先設定屬性數據即可,這就涉及到了自定義屬性。

需要設置的內容包括:上方 TextView 的標題、下方 TextView 的描述,以及描述在選中/未選中兩種狀態下的文本,因此屬性集需要定義標題、選中描述、未選中描述三項。在 res/values 目錄下新建 attrs.xml:

 <!--?xml version=1.0 encoding=utf-8?--> <resources> <declare-styleable name="combinationView"> <attr name="title" format="string" /> <attr name="desc_on" format="string" /> <attr name="desc_off" format="string" /> </declare-styleable> </resources>

接下來定義 Java 類來渲染布局、解析屬性集並對外提供修改狀態的方法。這裡該繼承哪個類呢?由於不是全新自定義,不需要 onMeasure 和 onDraw;布局也已寫死,不需要 ViewGroup 的 onLayout。其實只要繼承任意 ViewGroup 的子類即可——因為布局文件用的是 RelativeLayout,我們就繼承它;即便改成 LinearLayout 或 FrameLayout 也同樣可行。

 package com.example.combinationview; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.CheckBox; import android.widget.RelativeLayout; import android.widget.TextView; public class CombinationView extends RelativeLayout { private TextView tv_title; private TextView tv_desc; private CheckBox cb_status; // 命名空間,在引用這個自定義組件時需要用到 private String namespace = "https://schemas.android.com/apk/res/com.example.combinationview"; private String title; private String desc_on; private String desc_off; public CombinationView(Context context, AttributeSet attrs) { super(context, attrs); // 將自定義組合控件的布局渲染成 View View view = View.inflate(context, R.layout.layout_combinationview, this); tv_title = (TextView) view.findViewById(R.id.tv_title); tv_desc = (TextView) view.findViewById(R.id.tv_desc); cb_status = (CheckBox) view.findViewById(R.id.cb_status); title = attrs.getAttributeValue(namespace, title); desc_on = attrs.getAttributeValue(namespace, desc_on); desc_off = attrs.getAttributeValue(namespace, desc_off); System.out.println(title + ":" + desc_on + ":" + desc_off); if (title != null) { tv_title.setText(title); } if (desc_off != null) { tv_desc.setText(desc_off); } } /** 判斷是否被選中 */ public boolean isChecked() { return cb_status.isChecked(); } /** 設置選中的狀態 */ public void setChecked(boolean isChecked) { cb_status.setChecked(isChecked); if (isChecked) { tv_desc.setText(desc_on); } else { tv_desc.setText(desc_off); } } }

代碼思路很清晰:繼承 RelativeLayout 並復寫構造方法,先渲染布局視圖,再讀取屬性集的屬性並初始化到子控件,最後對外提供 isChecked() 與 setChecked(boolean) 兩個方法用於狀態的讀取與切換。(讀者不妨把父類改為 LinearLayout 或 FrameLayout 試試,一樣能實現。)

引用時先在 Activity 布局文件中定義,注意必須加上命名空間:

 <linearlayout android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical" xmlns:android="https://schemas.android.com/apk/res/android" xmlns:example="https://schemas.android.com/apk/res/com.example.combinationview"> <com.example.combinationview.combinationview android:id="@+id/cv_first" android:layout_height="wrap_content" android:layout_width="match_parent" example:desc_off="我是未被選中的描述1" example:desc_on="我是被選中的描述1" example:title="我是標題1"> </com.example.combinationview.combinationview> <com.example.combinationview.combinationview android:id="@+id/cv_second" android:layout_height="wrap_content" android:layout_width="match_parent" example:desc_off="我是未被選中的描述2" example:desc_on="我是被選中的描述2" example:title="我是標題2"> </com.example.combinationview.combinationview> <com.example.combinationview.combinationview android:id="@+id/cv_third" android:layout_height="wrap_content" android:layout_width="match_parent" example:desc_off="我是未被選中的描述3" example:desc_on="我是被選中的描述3" example:title="我是標題3"> </com.example.combinationview.combinationview> <com.example.combinationview.combinationview android:id="@+id/cv_fourth" android:layout_height="wrap_content" android:layout_width="match_parent" example:desc_off="我是未被選中的描述4" example:desc_on="我是被選中的描述4" example:title="我是標題4"> </com.example.combinationview.combinationview> </linearlayout>

可見代碼精簡了不少。需注意:引用自定義屬性集時,布局節點必須加上命名空間:

 xmlns:example=https://schemas.android.com/apk/res/com.example.combinationview

其中 example 是命名空間名稱,可任意取,但必須與控件中引用屬性的名稱一致;後半串是屬性集路徑,最後一個「/」後面必須是工程的包名,否則會報錯。

Activity 的業務邏輯代碼:

 package com.example.combinationview; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.app.Activity; public class MainActivity extends Activity implements OnClickListener { private CombinationView cv_first; private CombinationView cv_second; private CombinationView cv_third; private CombinationView cv_fourth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); cv_first = (CombinationView) findViewById(R.id.cv_first); cv_second = (CombinationView) findViewById(R.id.cv_second); cv_third = (CombinationView) findViewById(R.id.cv_third); cv_fourth = (CombinationView) findViewById(R.id.cv_fourth); cv_first.setOnClickListener(this); cv_second.setOnClickListener(this); cv_third.setOnClickListener(this); cv_fourth.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.cv_first: cv_first.setChecked(!cv_first.isChecked()); break; case R.id.cv_second: cv_second.setChecked(!cv_second.isChecked()); break; case R.id.cv_third: cv_third.setChecked(!cv_third.isChecked()); break; case R.id.cv_fourth: cv_fourth.setChecked(!cv_fourth.isChecked()); break; default: break; } } }

以上就是自定義組合控件的完整講解,雖然簡單卻非常常用。相比單純復制粘貼,封裝成組合控件不僅更「高大上」,還能提高代碼復用性、簡化結構並減少代碼量。

最後再補一個完整的標題欄(TitleBarView)實例:

 package com.xiong.demo1; import android.app.Activity; import android.os.Bundle; import android.view.View; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); TitleBarView titleBarView = (TitleBarView) findViewById(R.id.tbar_test); titleBarView.getTextViewRigth().setVisibility(View.GONE); titleBarView.setTitleBarChangerLiseter(new ItitleOnChangeLister() { @Override public void setLeftOnClickLister() { finish(); } @Override public void setRigthOnClickLister() { } }); } }
 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:xionglh="https://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <com.xiong.demo1.TitleBarView android:id="@+id/tbar_test" android:layout_width="match_parent" android:layout_height="45dp" xionglh:titleBar_center_text="首頁" xionglh:titleBar_center_textColor="@android:color/black" xionglh:titleBar_center_text_size="18sp" xionglh:titleBar_left_bg="@mipmap/left_back" xionglh:titleBar_right_text="安全中心" xionglh:titleBar_right_text_size="12sp"/> </LinearLayout>
 <?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="TitleBar"> <attr name="titleBar_center_text_size" format="dimension"/> <attr name="titleBar_center_text" format="string"/> <attr name="titleBar_center_textColor" format="color"/> <attr name="titleBar_left_bg" format="reference"/> <attr name="titleBar_right_text_size" format="dimension"/> <attr name="titleBar_right_text" format="string"/> <attr name="titleBar_right_textColor" format="color"/> </declare-styleable> </resources>
 package com.xiong.demo1; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; public class TitleBarView extends RelativeLayout { private ItitleOnChangeLister mItitleOnChangeLister; private ImageView mImgLeft; private TextView mTxtCenter, mTxtRigth; private float mTitleCenterTextSize; private String mTitleCenterText; private int mTitleCenterTextColor; private int mLeftBg; private float mTitleRigthTextSize; private String mTitleRigthText; private int mTitleRigthColor; public TitleBarView(Context context, AttributeSet attrs) { super(context, attrs); int defualtSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()); TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.TitleBar); mTitleCenterTextSize = typedArray.getDimension(R.styleable.TitleBar_titleBar_center_text_size, defualtSize); mTitleCenterText = typedArray.getString(R.styleable.TitleBar_titleBar_center_text); mTitleCenterTextColor = typedArray.getColor(R.styleable.TitleBar_titleBar_center_textColor, Color.RED); mLeftBg = typedArray.getResourceId(R.styleable.TitleBar_titleBar_left_bg, R.mipmap.left_back); mTitleRigthTextSize = typedArray.getDimension(R.styleable.TitleBar_titleBar_right_text_size, defualtSize); mTitleRigthText = typedArray.getString(R.styleable.TitleBar_titleBar_right_text); mTitleRigthColor = typedArray.getColor(R.styleable.TitleBar_titleBar_right_textColor, Color.RED); typedArray.recycle(); initView(); } private void initView() { mTxtCenter = new TextView(getContext()); mTxtCenter.setText(mTitleCenterText); mTxtCenter.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTitleCenterTextSize); mTxtCenter.setTextColor(mTitleCenterTextColor); LayoutParams centerParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); centerParams.addRule(RelativeLayout.CENTER_IN_PARENT, TRUE); addView(mTxtCenter, centerParams); mTxtRigth = new TextView(getContext()); mTxtRigth.setText(mTitleRigthText); mTxtRigth.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTitleRigthTextSize); mTxtRigth.setTextColor(mTitleRigthColor); LayoutParams rigthParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); rigthParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, TRUE); rigthParams.addRule(RelativeLayout.CENTER_VERTICAL, TRUE); addView(mTxtRigth, rigthParams); mImgLeft = new ImageView(getContext()); mImgLeft.setImageResource(mLeftBg); LayoutParams leftParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); leftParams.setMargins(6, 0, 0, 0); leftParams.addRule(RelativeLayout.CENTER_VERTICAL, TRUE); addView(mImgLeft, leftParams); View view = new View(getContext()); view.setMinimumWidth(1); view.setBackgroundColor(getResources().getColor(R.color.gray_767676)); LayoutParams viewParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 1); viewParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); addView(view, viewParams); mImgLeft.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mItitleOnChangeLister.setLeftOnClickLister(); } }); mTxtRigth.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mItitleOnChangeLister.setRigthOnClickLister(); } }); } public void setTitleBarChangerLiseter(ItitleOnChangeLister ititleOnChangeLister) { this.mItitleOnChangeLister = ititleOnChangeLister; } public ImageView getLeftImage() { return mImgLeft; } public TextView getTextViewCenter() { return mTxtCenter; } public TextView getTextViewRigth() { return mTxtRigth; } }
 package com.xiong.demo1; public interface ItitleOnChangeLister { void setLeftOnClickLister(); void setRigthOnClickLister(); }
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved