Android自定义控件方法详解
本文通过一个简单的例子来一步步教会大家实现android自定义控件,并详细讲解android自定义控件中的一些规则和方法,相信新入行的筒子们看完这篇文章能够对自定义控件有个较为全面的理解。
相信大家在开发过程中经常会遇到类似的布局,如下图,一般在项数不多的情况下,大家应该都会选择用LinearLayout嵌套两个TextView去实现每一项,但是如果项数很多呢?本人最近开发过程中就遇到了项数较多的情况。有人可能要说,可以用listView去实现,当然,这个问题我也想过了,如果中间又穿插着其他的布局样式,不是这么规整的一项一项摆着呢?listView实现起来恐怕就有点麻烦了。
所以,想到了用自定义控件去实现,顺便借此给大家讲讲自定义控件的具体实现方法。好了,废话不多说,直接上代码。
1.首先,你的class必须继承与View或者View的子类:
public class InputItemLayout extends LinearLayout{
}
我们可以看一下LinearLayout的继承关系:LinearLayout–>ViewGroup–>View
2.你至少需要提供一个构造函数,其中Context和AttributeSet作为参数。Context为上下文环境,AttributeSet为属性集,你在布局文件中指定的属性会包含在AttributeSet中从构造方法传入你的class中。
public InputItemLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
3.布局文件(如果需要)
<?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="match_parent"
android:gravity="center_vertical"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="horizontal" >
<TextView
android:id="@+id/tv_star_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000"
android:text="*"
android:visibility="gone"/>
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"