您的位置:首页 > 移动开发 > Android开发

在Android Studio使用自定义属性

2016-02-24 23:27 309 查看
步骤如下:
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);

}


参考:
1 android 自定义控件 使用declare-styleable进行配置属性(源码角度)
2 自定义View
3 Android 自定义控件在Android Studio中xmlns不识别

4 TextView的源码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: