这篇文章来介绍自定义组合控件,自定义组合控件的应用场景不少,好比当你的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); }