Android 自定义View(二)

标签属性篇

java代码:

Values attrs

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <attr name="TitleText" format="string|reference"/>
    <attr name="TitleTextColor" format="color|reference"/>
    <attr name="TitleTextSize" format="dimension|reference"/>

    <declare-styleable name="TestTitleView">
        <attr name="TitleText"/>
        <attr name="TitleTextColor"/>
        <attr name="TitleTextSize"/>
    </declare-styleable>
</resources>

View代码:

/**
 * Created by aierJun on 2017/2/15.
 */
public class TestTitleView extends RelativeLayout {
    private TextView back;
    private TextView title;

    public TestTitleView(Context context) {
        super(context);
    }

    public TestTitleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.test_text_title_view, this);
        back= (TextView)findViewById(R.id.back_test_view);
        title= (TextView)findViewById(R.id.title_test_view);
        TypedArray a=context.obtainStyledAttributes(attrs,R.styleable.TestTitleView);
        int textColor=a.getColor(R.styleable.TestTitleView_TitleTextColor, Color.BLUE);
        String textText=a.getString(R.styleable.TestTitleView_TitleText);
        float textSize=a.getDimension(R.styleable.TestTitleView_TitleTextSize,25);
        title.setTextSize(textSize);
        title.setTextColor(textColor);
        title.setText(textText);
        a.recycle();
    }

    public TestTitleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    public void setBackOnClickLister(OnClickListener lister){
        back.setOnClickListener(lister);
    }
}

Layout代码:

 <com.aierjun.test.view.TestTitleView
        android:id="@+id/test_testtitleview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:TitleTextSize="19sp"
        app:TitleText="aierjun">
    </com.aierjun.test.view.TestTitleView>

注意:

 TypedArray a=context.obtainStyledAttributes(attrs,R.styleable.TestTitleView);

最后

a.recycle();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值