前言
在学习了常见的控件和基本布局之后,我们对 Android 布局有了一定的了解,其中包括了一些概念性的东西,比如所有的控件都是直接或间接继承 View ,所有的布局都是直接或间接继承 ViewGroup .而 ViewGroup 也是继承自 View .于是,当我们系统自带的控件不满足我们的需求时,我们可以通过自定义控件来解决
自定义
也许像我一样刚开始学 Android 的同学不了解自定义控件的用途,比如一个 app 的标题栏都具有俩个按钮, 一个可以返回,一个可以点出菜单,中间一段文字信息,但是每次编写这样的页面都要重新编写代码未免太麻烦,就算是Ctrl + C 也会让代码更加冗长,于是我们用自定义的思想,把这个标题栏自定义成一个控件,类似 Button,TextView
下面看代码:
首先,新建一个布局t.xml,该布局作用画出控件的模样
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<TextView
android:text="我是小小鸟"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:text="点击"
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
为简单起见,我也就随便一些,同学们也可以换成自己想要的内容
之后也简单,就在activity_main.xml 文件中添加一句代码就够了
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<include layout="@layout/t"/>
</RelativeLayout>
是不是很简单呢,但是到了这里我们还不满足,上面添加的是普通的控件,Button的作用是给人点击的,至于我们编写的控件是用来干嘛的,可以是专门为了跳转某个界面或者退出等功能,所以我们还要给它加些功能,我们需要添加具有功能的自定义控件
新建一个 TitleLayout.java,在这里面实现逻辑
package com.example.hanlertest.domy;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
/**
* Created by Administrator on 2016/4/10.
*/
public class TitleLayout extends LinearLayout{
public TitleLayout(final Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.t,this);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context,"点我了!!",Toast.LENGTH_SHORT).show();
}
});
}
}
修改activity_main.xml的代码
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<com.example.hanlertest.domy.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
这里指定了控件的完整类名,且包名是不可省略的。。。。
自定义控件就这么简单,但是运用到实际做出好的产品却不是那么简单的,所以还是得继续深入学习啊