Android Studio自定义组合控件
在Android的开发中,为了能够服用代码,会把有一定共有特点的控件组合在一起定义成一个自定义组合控件。
本文就详细讲述这一过程。虽然这样的View的组合有一个粒度的问题。粒度太大了无法复用,粒度太小了又
达不到很好的复用的效果。不过,这些不在本文的讨论范围,需要读者自己去开发的实践中体会。
实例项目就选择一个登录注册的组件,这组件包括用户名、密码的文本输入框,还有登录和注册的按钮。这里
主要是为了讲解的需要,在选择服用代码的力度上可以不用参考。
默认的当一个新的项目创建以后就会生成一个Activity和与之相应的一个布局文件。这些已经足够使用。
这里假设你默认生成的Activity名称为MainActivity,布局文件为activity_main.xml。
首先,创建一个以LinearLayout为基类的View。这个View的名字就叫做LoginView。
/**
* Created by Bruce on 31/10/15.
*/
public class LoginView extends LinearLayout {
private Context _context;
public LoginView(Context context) {
this(context, null);
}
public LoginView(Context context, AttributeSet attrs) {
super(context, attrs);
_context = context;
//...
}
}
代码中包含了一个Context的成员,因为我们在后面需要用到。
之后,创建这个View需要的布局文件:
<?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:orientation="vertical"
android:padding="10dp">
<EditText android:id="@+id/userName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="User name" />
<EditText android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button android:id="@+id/loginButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Login" />
<Button android:id="@+id/signupButton"
android:layo