1. 程式人生 > >自定義view(自定義屬性)

自定義view(自定義屬性)

values下面創attr

<resources>
    <attr name="mText" format="string" />
    <attr name="mTextColor" format="color" />
    <attr name="mTextSize" format="dimension" />
    <declare-styleable name="MyTextView">
        <attr name="mText"/>
        <attr name="mTextColor"
/> <attr name="mTextSize"/> </declare-styleable> </resources>

獲取自定義屬性的值
package com.bwie.two;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect; import android.util.AttributeSet; import android.view.View; /** * 周旋 * 2017/9/28 11:19 */ public class MyView extends View{ private String mText; private int mTextColor; private int mTextSize; /** * 繪製時控制文字的控制範圍 * @param context */ private Rect mBound
; private Paint mpaint; public MyView(Context context) { this(context,null); } public MyView(Context context, AttributeSet attrs) { this(context, attrs,0); } public MyView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); //初始化 //獲取自定義屬性的值 TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyTextView, defStyleAttr, 0); mText = a.getString(R.styleable.MyTextView_mText); mTextColor = a.getColor(R.styleable.MyTextView_mTextColor, Color.BLACK); mTextSize = a.getDimensionPixelSize(R.styleable.MyTextView_mTextSize, 100); a.recycle(); //注意回收 mpaint = new Paint(); mpaint.setTextSize(mTextSize); mpaint.setColor(mTextColor); //獲得繪製文字的寬和高 mBound = new Rect(); mpaint.getTextBounds(mText, 0, mText.length(), mBound); } public MyView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawText(mText,getWidth()/2-mBound.width()/2,getHeight()/2+mBound.height()/2,mpaint); } }

xml 中使用

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
xmlns:openxu="http://schemas.android.com/apk/res-auto"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.bwie.two.MainActivity">
    <com.bwie.two.MyView
android:layout_width="200dip"
android:layout_height="100dip"
openxu:mTextSize="25sp"
openxu:mText="i love you"
openxu:mTextColor ="#0000ff"
android:background="#ff0000"/>
</RelativeLayout>