自定义控件

引入布局

新建一个布局title.xml



    
    

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

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


    

在主布局中只需要通过一行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。


    

添加自定义控件和添加普通控件的方式基本是一样的,只不过在添加自定义控件的时候需要指明控件的完整类名,包名在这里是不可以省略的


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() {
			
			@Override
			public void onClick(View v) {
				((Activity) getContext()).finish();
			}
		});
		titleEdit.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Toast.makeText(getContext(), "You clicked Edit button", Toast.LENGTH_SHORT).show();
			}
		});
	}

}



你可能感兴趣的:(Android)