Android开发 - 用TypeArray类方法与xml传自定义属性应用解析
TypeArray的介绍
-
TypeArray是一个数组容器,在这个容器中装由
context.obtainAttributes(AttributeSet set, int[] attrs)
函数获取到的属性值,用完之后需要调用typedArray.recycle();
函数回收资源。 -
context.obtainStyledAttributes(AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes)
:- 参数解析:
- set:xml文件中的定义的属性集(理解为键值对<key, val>)
- attrs:要取出typeArray的目标属性(理解为键)
- 参数解析:
TypeArray的使用
-
自定义xml属性集代码示例:在资源文件values 下创建一个自定义xml(例如myattrs.xml)
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MyXml"> <attr name="text" format="string" /> <attr name="textColor" format="color"/> </attr> </declare-styleable> </resources>
-
自定义java代码文件示例:在资源文件loot下创建一个自定义java代码文件(例如MyView.java)
package tool; import android.content.Context; import android.util.AttributeSet; public class DrawView extends androidx.appcompat.widget.AppCompatImageView { private int mTextColor; private String mText; private Context mContext; private AttributeSet mAttrs; public DrawView(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; mAttrs = attrs; init(context); } public void init(Context context) { TypedArray typedArray = mContext.obtainStyledAttributes(mAttrs, R.styleable.MyXml); mText = typedArray.getText(R.styleable.MyXml_text); //MyXml_text:使用'_'分割元素组与kay mTextColor = typedArray.getColor(R.styleable.MyXml_textColor, Color.WHITE); typedArray.recycle(); //回收资源 //设置画笔 mPaint = new Paint(); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeCap(Paint.Cap.ROUND); mPaint.setStrokeWidth(25); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //传入自定义属性应用 mPaint.setColor(mTextColor); canvas.drawText(mText, getWidth() / 2, getHeight() / 2, mPaint); } }
-
自定义xml布局代码示例:在资源文件layout下创建一个自定义xml(例如activity_main.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:myText="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" <tool.MyView android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="@dimen/small_padding" android:layout_centerInParent="true" myText:text="1234" myText:textColor="@color/green" /> </LinearLayout>
-
随后在启动类内导入实例化MyView类进行show即可