引入布局

新建一个布局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动态加载Dex技术基础
  2. Android 中自定义控件和属性(attr.xml,declare-styleable,TypedA
  3. Android studio的常见布局
  4. Android:布局(线性布局LinearLayout)
  5. 在控件的任意位置显示图片
  6. Android加载Gif和ImageView的通用解决方案:android-gif-drawable:G
  7. 使用架包实现android异步加载图片
  8. 自定义SeekBarPreference控件(老外出品,直接在preferences文件中

随机推荐

  1. Android获取设备已安装的应用
  2. android 判断字符串是否为空与比对["=="
  3. Android软件集合
  4. Android应用使用百度地图API
  5. android 音频开发之混响效果
  6. android音乐播放器怎么搜索SD卡上的音乐
  7. Android封装BaseActivity
  8. Android(安卓)LBS系列01 使用Location Ma
  9. Android(安卓)sdk适配指南心得
  10. android中打开本地doc、pdf、ppt、text等