前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >用TypedArray给自定义控件配置属性

用TypedArray给自定义控件配置属性

作者头像
提莫队长
发布2019-02-21 15:07:41
7300
发布2019-02-21 15:07:41
举报
文章被收录于专栏:刘晓杰刘晓杰

(仅仅只是整理,以后用到直接来翻就行了) 比如有这样一个自定义控件(layout文件就不看了)

代码语言:javascript
复制
public class TitleView extends LinearLayout {
    public ImageView themeTitleLeft;
    private TextView themeTitle;
    private ImageView themeTitleRight;

    public TitleView(Context context) {
        this(context, null);
    }

    public TitleView(final Context context, AttributeSet attrs) {
        super(context, attrs);
        inflate(context, R.layout.theme_title, this);

        themeTitle = (TextView) findViewById(R.id.theme_title);
        themeTitleLeft = (ImageView) findViewById(R.id.theme_title_left);
        themeTitleRight = (ImageView) findViewById(R.id.theme_title_right);

        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.title);
        String name = ta.getString(R.styleable.title_name);
        themeTitle.setText(name);
        ta.recycle();
    }
}

那R.styleable.title和R.styleable.title_name又是怎么配置的呢? 当然是在values文件夹下新建attrs.xml

代码语言:javascript
复制
    <declare-styleable name="title">
        <attr name="name" format="string"/>
    </declare-styleable>

生成TypedArray是用的declare-styleable的name,生成对应的string是在两个name中加下划线 用法

代码语言:javascript
复制
<com.*******.TitleView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        app:name="订单"/>//-----------------添加app:
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年05月06日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档