在Android Studio使用自定义属性

步骤如下:
1 在res/values/ 下建立一个保存属性的文件attrs.xml (名称任意)
2 使用declare-styleable给自定义控件添加自定义属性
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="mTitleText" format="string"/>
<attr name="mTitleTextColor" format="color"/>
<attr name="mTitleTextSize" format="dimension"/>
<declare-styleable name="CustomStyleView">
<attr name="mTitleText" />
<attr name="mTitleTextColor" />
<attr name="mTitleTextSize" />
</declare-styleable>
</resources>
3 在布局文件中使用自定义属性:
3.1 在布局文件头中添加
xmlns:custom="http://schemas.android.com/apk/res-auto"
3.2 在自定义控件中使用自定义属性:
<com.smiling.myview.MyStyleView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
custom:mTitleText="sss"
custom:mTitleTextColor="#ff0000"
custom:mTitleTextSize="40sp"
/>

4 在自定义View中获取自定义属性对应的值
public MyStyleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
Log.i(TAG, "MyStyleView3");

/**
* 获得我们所定义的自定义样式属性
*/
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomStyleView, defStyleAttr, 0);
int n = a.getIndexCount();
for (int i = 0; i < n; i++)
{
int attr = a.getIndex(i);
switch (attr)
{
case R.styleable.CustomStyleView_mTitleText:

mTitleText = a.getString(attr);

break;
case R.styleable.CustomStyleView_mTitleTextColor:
// 默认颜色设置为黑色
mTitleTextColor = a.getColor(attr, Color.BLACK);
break;
case R.styleable.CustomStyleView_mTitleTextSize:
// 默认设置为16sp,TypeValue也可以把sp转化为px
mTitleTextSize = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));
break;

}

}
a.recycle();

/**
* 获得绘制文本的宽和高
*/
mPaint = new Paint();
mPaint.setTextSize(mTitleTextSize);
// mPaint.setColor(mTitleTextColor);
mBound = new Rect();
mPaint.getTextBounds(mTitleText, 0, mTitleText.length(), mBound);

}

参考:

4 TextView的源码

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值