创建自定义控件
Android 布局中很多时候系统自带的控件不能满足我们的需求
需要使用自定义控件。
按照以下三个步骤,可以自定义控件:以创建自定义titlebar控件为例
准备工作:创建一个app案例工程,不在赘述。
效果图:
1. 创建自定义控件对应的对象
- 重写构造方法
- 加载布局文件
- 设置监听事件
public class TitleBar extends LinearLayout implements View.OnClickListener {
private Button bt_title_back;
private Button bt_title_edit;
private Button tv_title_text;
private Context mycontext;
// 在此构造方法中初始化视图
public TitleBar(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
this.mycontext = context;
LayoutInflater.from(context).inflate(R.layout.diy_title,this);
bt_title_back = (Button) findViewById(R.id.bt_title_back);
bt_title_edit = (Button) findViewById(R.id.bt_title_edit);
bt_title_back.setOnClickListener(this); //通过实现监听接口的方式设置监听
bt_title_edit.setOnClickListener(this);
}
//监听方法
@Override
public void onClick(View v) {
if(v==bt_title_back) {
Toast.makeText(mycontext, "返回", Toast.LENGTH_SHORT).show();
}else if(v ==bt_title_edit) {
Toast.makeText(mycontext, "编辑", Toast.LENGTH_SHORT).show();
}
}
}
2. 创建自定义控件对应的布局件
布局视图:
![]()
布局文件:diy_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="@android:color/darker_gray"
android:orientation="horizontal">
<Button
android:id="@+id/bt_title_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:text="返回" />
<TextView
android:id="@+id/tv_title_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="标题栏"
android:textSize="30sp" />
<Button
android:id="@+id/bt_title_edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:text="编辑" />
</LinearLayout>
3. 主Activiy中的布局文件中使用 自定义视图:activity_main.xml
<com.example.a02diycontroller.ui.TitleBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
></com.example.a02diycontroller.ui.TitleBar>