這篇文章來介紹自定義組合控件,自定義組合控件的應用場景不少,好比當你的UI以下時:android
假若不使用組合控件,則須要在XML文件中聲明4個TextView和4個EditText,而使用了組合控件,則只須要四個便可,方便不少。函數
自定義組合控件比自定義控件容易許多,由於其不涉及到相關的繪圖操做,只須要將已有的控件組合便可,接下來介紹其設計方法:字體
自定義控件的Layout文件設計和ListView的Item相似,如上圖所示的設計,以下便可:spa
<?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="wrap_content" android:orientation="horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="match_parent" android:id="@+id/describe_tv" android:gravity="bottom" android:paddingBottom="5dp"/> <EditText android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/describe_et"/> </LinearLayout>
這裏的自定義屬性的聲明以及獲取均和自定義控件相同,如本例中,須要修改的即是TextView的文字以及文字的大小,那麼屬性聲明文件以及屬性獲取代碼,以下便可:設計
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="DescribeView"> <attr name="text" format="string"/> <attr name="textsize" format="dimension"/> </declare-styleable> </resources>
private void initattr(Context context, AttributeSet attrs) { TypedArray typedArray=context.obtainStyledAttributes(attrs,R.styleable.DescribeView); String text=typedArray.getString(R.styleable.DescribeView_text); tv.setText(text); float size=typedArray.getDimension(R.styleable.DescribeView_textsize,30); tv.setTextSize(TypedValue.COMPLEX_UNIT_PX,size); }
這裏須要注意的是,tv.setTextSize默認設定的是dp值,而getDimension獲取的是px值,因此在setTextSize的時候,要設定size的類型爲px,不然會出現字體過大的狀況。code
想要在Java文件中修改屬性值,只須要設置相關的public函數便可,如orm
public void SetText(String s) { tv.setText(s); }