步骤:
1、编写布局文件
2、确定需要自定义的属性,在value-attrs文件中命名相关属性并确定数据类型
3、编写java文件、继承容器
4、在布局中使用
public class MyMenuView extends RelativeLayout {
private ImageView my_menu_icon;//前边的图标
private TextView my_menu_title;//主标题
private TextView my_menu_subtitle;//副标题
private Context context;
private String txtTitle;
private String txtSubTitle;
private int resIcon;
public MyMenuView(Context context) {
super(context);
this.context = context;
}
public MyMenuView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
LayoutInflater.from(context).inflate(R.layout.custom_view_my_tab, this, true);//找到布局
my_menu_icon = findViewById(R.id.cus_front_icon);
my_menu_title = findViewById(R.id.cus_top_title);
my_menu_subtitle = findViewById(R.id.cus_sub_title);
TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.CustomTitleBar);//找到style标签
if (attributes != null) {
txtSubTitle = attributes.getString(R.styleable.CustomTitleBar_cus_subtitle_text);//找到标签下元素
my_menu_subtitle.setText(txtSubTitle);
txtTitle = attributes.getString(R.styleable.CustomTitleBar_cus_title_text);
my_menu_title.setText(txtTitle);
resIcon = attributes.getResourceId(R.styleable.CustomTitleBar_cus_front_icon, 0);
Glide.with(context).load(context.getResources().getDrawable(resIcon)).into(my_menu_icon);//glide加载本地图片资源,其他方式也可
attributes.recycle();
}
}
//可自定义方法,在代码中对控件属性进行设置
public void setValue(String url, String title, String subtitle) {
my_menu_title.setText(title);
my_menu_subtitle.setText(subtitle);
Glide.with(context).load(url).into(my_menu_icon);
}
}
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomTitleBar">
<attr name="cus_front_icon" format="reference|integer" />
<attr name="cus_title_text" format="string" />
<attr name="cus_subtitle_text" format="string" />
</declare-styleable>
</resources>