自定义控件

来源:互联网 发布:当代网络小说家排行榜 编辑:程序博客网 时间:2024/05/16 14:48

引入布局

新建一个布局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="@drawable/title_bg"    >        <Button        android:id="@+id/title_back"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:layout_margin="5dip"        android:background="@drawable/back_bg"        />        <TextView        android:id="@+id/title_text"        android:layout_width="0dp"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:layout_weight="1"        android:gravity="center"        android:text="Title Text"        android:textColor="#fff"        android:textSize="24sp"        />        <Button        android:id="@+id/title_Edit"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:layout_margin="5dip"        android:background="@drawable/edit_bg"        />    </LinearLayout>

android:background用于为布局或控件指定一个背景,可以使用颜色或图片来进行填充

android:layout_margin这个属性可以指定控件在上下左右方向上偏移的距离,当然也可以使用android:layout_marginLeft或android:layout_marginTop等属性来单独指定控件在某个方向上偏移的距离


    <include layout="@layout/title" />

在主布局中只需要通过一行include语句就可以将布局引入进来了


自定义控件


新建TitleLayout继承自LinearLayout,让它成为我们自定义的标题栏控件

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。


    <com.example.uicustomview.TitleLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        ></com.example.uicustomview.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 View.OnClickListener() {@Overridepublic void onClick(View v) {((Activity) getContext()).finish();}});titleEdit.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Toast.makeText(getContext(), "You clicked Edit button", Toast.LENGTH_SHORT).show();}});}}



0 0