在Android Studio使用自定义属性
2016-02-24 23:27
309 查看
步骤如下:
1 在res/values/
下建立一个保存属性的文件attrs.xml (名称任意)
2
使用declare-styleable给自定义控件添加自定义属性:
3
在布局文件中使用自定义属性:
3.1
在布局文件头中添加
3.2
在自定义控件中使用自定义属性:
4
在自定义View中获取自定义属性对应的值
参考:
1 android 自定义控件 使用declare-styleable进行配置属性(源码角度)
2 自定义View
3 Android 自定义控件在Android Studio中xmlns不识别
4 TextView的源码
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的源码
相关文章推荐
- 编译android源码6---运行android编译源码
- Android 线程 Looper.prepare()、Looper.loop() Looper.prepare()和Looper.loop() —深入版
- Android 遍历文件夹,搜索指定扩展名的文件
- android的Log输出
- Android中检测当前是否为主线程
- Android中ScrollView嵌套ListView
- #Android学习#启动、绑定及跨应用启动Service
- [android] 短信发送器
- 封装使用ViewHolder模式的Adapter组件,及用其快速实现聊天界面
- Android中GridView实现长按多选功能
- Android编译过程详解(三)
- Android 图片处理方法
- Android编译过程详解(二)
- Android编译过程详解(一)
- Android Studio修改字体大小的方法
- 第2章 Android Dalvik 实战apktool反编译
- 《Android源码设计模式》读书笔记 (18) 第18章 代理模式
- Android的LayoutInflater和findViewById()的详解
- Android ActivityGroup
- 打开Android C文件中的LOG