Android学习——自定义控件(二)

时间:2023-03-10 03:44:29
Android学习——自定义控件(二)

这篇文章来介绍自定义组合控件,自定义组合控件的应用场景很多,比如当你的UI如下时:

Android学习——自定义控件(二)

倘若不使用组合控件,则需要在XML文件中声明4个TextView和4个EditText,而使用了组合控件,则只需要四个即可,方便很多。

自定义组合控件比自定义控件容易许多,因为其不涉及到相关的绘图操作,只需要将已有的控件组合即可,接下来介绍其设计方法:

绘制Layout文件


自定义控件的Layout文件设计和ListView的Item类似,如上图所示的设计,如下即可:

<?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,否则会出现字体过大的情况。

在Java文件中修改属性值


想要在Java文件中修改属性值,只需要设置相关的public函数即可,如

public void SetText(String s)
{
tv.setText(s);
}