引入布局

新建一个布局title.xml

<?xml version="1.0" encoding="utf-8"?>        

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() {@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();}});}}



更多相关文章

  1. Android初始化语言 (init.*.rc、init.conf文件格式)
  2. Android(安卓)中全局键的处理GlobalKeyManager
  3. android使用指定的字体
  4. android 加载图片轻松避免OOM(out of memory)
  5. Android动态加载Dex技术基础
  6. ListView的优化就这么多了
  7. Android(安卓)中自定义控件和属性(attr.xml,declare-styleable,T
  8. android使用WebView显示sdcard的html文件
  9. Android(安卓)自定义阴影效果详解及实例

随机推荐

  1. Android关机流程解析---从reboot说起
  2. android告别篇-对于源码我的一些看法
  3. Android 系统内存扫盲点
  4. Facebook推出强大Android图片库Fresco 自
  5. Android中各种组件的生命周期
  6. Android当中切换图片
  7. Android国内开发者陷盈利困局 版本过多支
  8. WebView之js调用Android类的方法传递数据
  9. ExifInterface使用,Android(安卓)2.0新增
  10. Android(安卓)6.0 BluetoothAdapter.star