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