Android自定义组合控件

步骤:
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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值