- public class TitleLayout extends LinearLayout {
- public TitleLayout(Context context, AttributeSet attrs) {
- super(context, attrs);
- LayoutInflater.from(context).inflate(R.layout.title, this);
- }
- }
首先我们重写了 LinearLayout 中的带有两个参数的构造函数,在布局中引入 TitleLayout 控件就会调用这个构造函数。然后在构造函数中需要对标题栏布局进行动态加载,这就要借助 LayoutInflater 来实现了。通过 LayoutInflater 的 from() 方法可以构建出一个 LayoutInflater 对象,然后调用 inflate() 方法就可以动态加载一个布局文件,inflate() 方法接收两个参数,第一个参数是要加载的布局文件的 id,这里我们传入 R.layout.title,第二个参数是给加载好的布局再添加一个父布局,这里我们想要指定为 TitleLayout,于是直接传入 this。
现在自定义控件已经创建好了,然后我们需要在布局文件中添加这个自定义控件,修改 activity_main.xml 中的代码,如下所示:
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
-
- <com.example.uicustomviews.TitleLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- ></com.example.uicustomviews.TitleLayout>
-
- </LinearLayout>
添加自定义控件和添加普通控件的方式基本是一样的,只不过在添加自定义控件的时候我们需要指明控件的完整类名,包名在这里是不可以省略的。
然后我们俩尝试为标题栏中的按钮注册点击事件,修改 TitleLayout 中的代码,如下所示:
- public class TitleLayout extends LinearLayout {
-
- public TitleLayout(Context context, AttributeSet attrs) {
- super(context, attrs);
- LayoutInflater.from(context).inflate(R.layout.title, this);
- Button titleBack = (Button) findViewById(R.id.title_back);
- Button titleEdit = (Button) findViewById(R.id.title_edit);
- titleBack.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- ((Activity) getContext()).finish();
- }
- });
- titleEdit.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- Toast.makeText(getContext(), "You clicked Edit button", Toast.LENGTH_SHORT).show();
- }
- });
- }
- }
首先还是通过 findViewById() 方法得到按钮的实例,然后分别调用 setOnClickListener() 方法给两个按钮注册了点击事件,当点击返回按钮时销毁掉当前的 Activity,当点击编辑按钮时弹出一段文本。
这样的话,每当我们在一个布局中引入 TitleLayout,返回按钮和编辑按钮的点击事件就已经自动实现好了,也是省去了很多编写重复代码的工作。