创建自定义控件

来源:互联网 发布:淘宝店铺发布产品 编辑:程序博客网 时间:2024/06/05 07:49

显示效果:


1.首先第一步,新建一个布局title.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"    android:background="#3cb371">    <ImageButton        android:contentDescription="@string/app_name"        android:id="@+id/title_back"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:background="@drawable/iconfont_pre2"        android:layout_margin="4dip"/>    <TextView        android:id="@+id/title_textView"        android:layout_width="0dp"        android:layout_height="35dp"        android:layout_weight="1"/>    <ImageButton        android:contentDescription="@string/item_option"        android:id="@+id/title_options"        android:layout_width="48dp"        android:layout_height="wrap_content"        android:background="@drawable/iconfont_menu2"        android:layout_margin="5dp" /></LinearLayout>
我们在LinearLayout中添加了两个ImageButton和一个TextView,左边ImageView用来返回,右边ImageView可以用来显示菜单(但是现在我还不会添加。。。),中间TextView可以用来显示一段标题文本。

其中android:layout_margin的属性是指定控件上下左右方向上的偏移,也可以用android:layout_marginLeft来专门指定某个方向上的偏移。

那么如何在程序中引用这个标题栏呢?代码如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical" android:layout_width="match_parent"    android:layout_height="match_parent">
<include layout="@layout/title"/>
当然不要忘记在MainActivity中将系统自带的标题栏隐藏掉:requestWindowFeature(Window.FEATURE_NO_TITLE)

2.但是返回按钮的功能基本是不会改变的,每次引用title总要重新注册一遍返回Button的功能造成了代码的不必要重复,所以我们通过自定义控件的方法来解决这个问题

新建Title继承自LinearLayout:

public class Title extends LinearLayout {    public Title(Context context,AttributeSet attrs){        super(context, attrs);        LayoutInflater.from(context).inflate(R.layout.title, this);        ImageButton title_back=(ImageButton)findViewById(R.id.title_back);        title_back.setOnClickListener(new View.OnClickListener(){            @Override            public void onClick(View v){                ((Activity)getContext()).finish();            }        });        ImageButton title_options=(ImageButton)findViewById(R.id.title_options);        title_options.setOnClickListener(new View.OnClickListener(){            @Override            public void onClick(View v){                //options            }        });    }}
这里我们重写了含两个参数的构造函数,通过LayoutInflater的from()方法可以构建出一个LayoutInflater对象,然后调用inflate()方法就可以动态加载一个布局文件,inflate接收两个参数,一个参数是要加载的布局文件的id,这里我们传入R.layout.title,第二个参数是给加载好的布局再添加一个父布局,这里我们想指定为Title,于是传入this。

然后的步骤就很简单了,就是在Title中添加Button的点击事件,这里略过。

3.第三步是在需要引用自定义标题栏的布局中添加title,代码如下:

<com.example.niu.uilayouttest.Title    android:layout_width="match_parent"    android:layout_height="wrap_content"></com.example.niu.uilayouttest.Title>
这里要写全包名。

0 0
原创粉丝点击