自定义属性
来源:互联网 发布:java 打war包命令 编辑:程序博客网 时间:2024/05/29 18:50
自定义属性
<?xml version="1.0" encoding="utf-8"?><resources> <!--定义名字叫MyView属性集合--> <declare-styleable name="MyView"> <!--定义一个名字叫my_name并且类型是string的属性--> <attr name="my_name" format="string"/> <attr name="my_age" format="integer"/> <attr name="my_bg" format="reference|color"/> </declare-styleable></resources>
<com.example.makura.myapplication.MyView mydiyattr:my_age="100" mydiyattr:my_name="zhangsan" mydiyattr:my_bg="@drawable/testimg" android:layout_width="match_parent" android:layout_height="match_parent" />
public class MyView extends View { private int myAge; private String myName; private Bitmap myBg; public MyView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); /** * 获取属性的3种方式 * 1.用命名空间去获取 * 2.遍历属性集合 * 3.使用系统工具,获取属性 */ // 第一种 String name = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto", "my_name"); String age = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto", "my_age"); String bg = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto", "my_bg"); Log.e("name = ", name); Log.e("age = ", age); Log.e("bg = ", bg); Log.e("分割线1", "-----------------------"); // 第二种 for (int i = 0; i < attrs.getAttributeCount(); i++) { String attributeName = attrs.getAttributeName(i); String attributeValue = attrs.getAttributeValue(i); Log.e(attributeName + " == ", attributeValue); } Log.e("分割线2", "-----------------------"); // 第三种 TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyView); for (int i = 0; i < typedArray.getIndexCount(); i++) { int index = typedArray.getIndex(i); switch (index) { case R.styleable.MyView_my_name: myName = typedArray.getString(index); break; case R.styleable.MyView_my_age: myAge = typedArray.getInt(index,0); break; case R.styleable.MyView_my_bg: Drawable drawable = typedArray.getDrawable(i); BitmapDrawable bd = (BitmapDrawable) drawable; myBg = bd.getBitmap(); break; } } //回收 typedArray.recycle(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint paint = new Paint(); paint.setColor(Color.RED); paint.setTextSize(30); canvas.drawBitmap(myBg,0,0,paint); canvas.drawText("myName is"+myName+" myage="+myAge,150,150,paint); }}
阅读全文
0 0
- 自定义属性
- 自定义属性
- 自定义属性
- 自定义属性
- 自定义属性
- 自定义属性
- 自定义属性
- 自定义属性
- 自定义属性
- 自定义属性
- 自定义属性
- 自定义属性
- 自定义属性
- 自定义属性
- 自定义属性
- 自定义属性
- 自定义属性
- 自定义属性
- CF
- python 3 安装igraph
- Spring之——两种任务调度Scheduled和Async
- 欢迎使用CSDN-markdown编辑器
- java集合
- 自定义属性
- ThreadPoolExecutor机制【转】
- Ubuntu 16.04 LTS + GTX1060 + CUDA8.0 解决循环登录问题
- 在二叉查找树中插入节点
- C# WeifenLuo.WinFormsUI.Docking控件使用
- Java中的序列化是什么意思?有什么好处?
- 开源博客 EumJi-blog 简介篇
- POJ-3176-Cow Bowling-(简单dp)
- Mybatis的pageHelper插件实现分页