android-R.styleable(应用)
2016-06-21 15:03
399 查看
在res/values 文件下定义一个attrs.xml 文件
demo下载
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="CusView"> <attr name="textColor" format="color" /> <attr name="textSize" format="dimension" /> </declare-styleable> </resources>布局文件引用:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:cus="http://schemas.android.com/apk/res/com.z.boolattribute" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <!-- com.z.boolattribute 是我们包名 --> <com.z.boolattribute.CusView android:layout_width="fill_parent" android:layout_height="wrap_content" cus:textColor="#ff00cc" cus:textSize="20sp" > </com.z.boolattribute.CusView> </LinearLayout>之定义view
package com.z.boolattribute; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Rect; import android.util.AttributeSet; import android.view.View; //com.z.boolattribute.CusView public class CusView extends View { private Paint mPaint; private Context mContext; public CusView(Context context) { super(context); mPaint = new Paint(); } public CusView(Context context, AttributeSet attrs) { super(context); mPaint = new Paint(); TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.CusView); // 设置默认值 int textColor = array.getColor(R.styleable.CusView_textColor, 0Xff00cc); float textSize = array.getDimension(R.styleable.CusView_textSize, 36); mPaint.setTextSize(textSize); mPaint.setColor(textColor); array.recycle(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 设置填充 mPaint.setStyle(Style.FILL); // 画一个矩形,前俩个是矩形左上角坐标,后面俩个是右下角坐标 canvas.drawRect(new Rect(10, 10, 100, 100), mPaint); mPaint.setColor(Color.BLUE); // 绘制文字 canvas.drawText("Look Me", 10, 120, mPaint); } }
package com.z.boolattribute; import android.app.Activity; import android.os.Bundle; public class TwoActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_two); } }
demo下载
相关文章推荐
- android中颜色渐变动画
- Android通知栏微技巧,那些你所没关注过的小细节
- Android获取手机内部存储空间和外部存储空间
- 浅谈Material Design
- Intellij下载及导入Android工程
- Android LinearLayout比例计算
- 利用AsyncTask高效异步加载图片,适用于ListView 和GridView
- Android Activity生命周期
- Android studio设置字体大小和更改背景
- Android编辑框被输入法遮盖,有效的处理办法
- 华为MT7 Logcat 不输出&少输出问题
- Android开发中常用计算缓存数据和清除缓存数据工具类
- Android应用如何开机自启动、自启动失败原因
- Android事件分发、拦截与处理的理解
- AndroidStudio打包处理
- MVP in android
- android material design
- 你需要知道的Android拍照适配方案
- 常用android依赖库
- Android中判断当前应用程序是否在运行 推送时进行判断