自定义控件的基本方法(以标题栏为例)

来源:互联网 发布:模糊pid控制算法 编辑:程序博客网 时间:2024/05/01 21:35

我们所用的所有控件都是直接或间接的继承自View的,所有的Layout都是直接或间接继承自ViewGroup的。View是Android中最基本的一种组件。


1.创建自定义控件xml文件,在xml文件中创建你需要自定义的控件内容

e.g.

<?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="#000000"    android:orientation="horizontal">    <Button        android:id="@+id/title_back"        android:text="Back"        android:gravity="center"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:layout_margin="5dp" />    <TextView        android:id="@+id/title_text"        android:text="Title Text"        android:textSize="24sp"        android:gravity="center"        android:layout_width="0dp"        android:layout_height="wrap_content"        android:layout_weight="1"        android:layout_gravity="center" />    <Button        android:id="@+id/title_edit"        android:text="Edit"        android:gravity="center"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center|top"        android:layout_margin="5dp" /></LinearLayout>

2.隐藏Android自带的标题栏功能

在主Activity中添加

ActionBar actionBar = getSupportActionBar();if (actionBar != null){    actionBar.hide();}

3.重写构建函数(当Layout中引入自定义控件就会调用这个函数)

这里需要对标题栏Layout进行动态加载,借助LayoutInflater来实现。

通过LayoutInflater的form()方法可以构建出一个LayoutInflater对象,然后调用inflater方法就可以动态加载一个Layout文件,inflater中的第一个参数为需要加载的Layout的id,

第二个参数为加载好的Layout再添加一个父Layout。

public class TitleLayout extends LinearLayout {    public TitleLayout(Context context, AttributeSet attributeSet){        super(context, attributeSet);        LayoutInflater.from(context).inflate(R.layout.title, this);        link_btn();    }    public void link_btn(){        Button button_1 = (Button)findViewById(R.id.title_back);        Button button_2 = (Button)findViewById(R.id.title_edit);        button_1.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                ((Activity)getContext()).finish();            }        });        button_2.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                Toast.makeText(getContext(), "You clicked Edit button!",                        Toast.LENGTH_SHORT).show();            }        });    }

阅读全文
0 0
原创粉丝点击