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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章