android学习笔记--创建自定义控件

来源:互联网 发布:如何避免网络陷阱 编辑:程序博客网 时间:2024/05/18 02:20

我们知道,android中所有的控件,都是继承自View的,当系统中提供的控件不够用时,我们可以利用这个继承关系,自定义控件。


android界面和iphone界面比较大的一点不同,就是安卓在HOME键的右边有一个返回键,可以销毁当前活动,并返回上一个活动,但是有些时候,我们需要在软件界面的左上角标题上定义一个返回按钮,点击后,返回上一个界面。

由于多个界面可能都需要这样一个按钮,我们就自定义一个标题。


我们新建一个xml布局文件,如下

<?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"    >    <Button         android:id="@+id/title_back"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_margin="5dp"        android:layout_gravity="center"        android:text="back"                />   <TextView        android:id="@+id/title_text"       android:layout_width="wrap_content"       android:layout_height="wrap_content"       android:text="aatitle_text"       android:layout_gravity="center"       android:layout_weight="1"       />   <Button       android:id="@+id/title_create"       android:layout_width="wrap_content"       android:layout_height="wrap_content"       android:layout_margin="5dp"       android:layout_gravity="center"              android:text="new" /></LinearLayout>

定一个一个标题,含有两个按钮,一个文本框。其中TextView 设置了weight=1,这表明,在水平方向上(Linearlayout默认是水平的),两个Button的宽度wrap_content分配完后,剩下的宽度都给TextView,layout_gravity=“center”表明在竖直方向,三个控件都是居中的



定义好标题布局文件后,只需要在你需要添加标题的页面对应的layout布局文件中加上一行代码:

<include layout="@layout/你所定义的布局文件的文件名"/>


然后在其对应的Activity类中的Oncreate方法下,将系统自带的标题隐藏掉


requestWindowFeature(Window.FEATURE_NO_TITLE);


运行后就发现达到了所要的效果。



但是这样问题又来了,你在那么多个Activity的页面中,定义了back和new按钮后,你还需要在每个Activity里定义一个Button的监听器,还要写点击后触发的back事件,这样很麻烦。


这时候,就需要用到自定义控件了,

先写一个TitleLayout类

public class TitleLayout extends LinearLayout{


public TitleLayout(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
LayoutInflater.from(context).inflate(R.layout.title_layout, this);
Button title_back=(Button) findViewById(R.id.title_back);
Button title_create=(Button) findViewById(R.id.title_create);
title_back.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
((Activity)getContext()).finish();
}
});
title_create.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getContext(),"create a XXX", Toast.LENGTH_LONG).show();
}
});
}


}


此外,还需要在activity_main中添加自定义控件


<com.example.titletest.TitleLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    ></com.example.titletest.TitleLayout>


这样,就不需要在每个页面中都单独的编写back和create两个按钮的点击事件了。

0 0
原创粉丝点击