歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android自定義view屬性

Android自定義view屬性

日期:2017/3/1 9:53:58   编辑:Linux編程

延續上一篇的Android自定義view(見http://www.linuxidc.com/Linux/2013-08/88918.htm),現在給view添加自己的屬性。

android自帶的view都有自己的屬性如
android:id="@+id/myView"
android:layout_width="200dp"
android:layout_height="550dp"
android:focusable="true"
android:clickable="true"

但是我們自己定義的view是否能添加屬性呢?答案是可以的。

下面直接進入主題:
第一步:在res/values文件下定義一個attrs.xml文件.代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView">
<attrname="textColor" format="color"/>
<attrname="textSize" format="dimension"/>
</declare-styleable>
</resources>

第二步:我們在MyView.java代碼修改如下,其中下面的構造方法是重點public MyView(Context context,AttributeSet attrs),我們獲取定義的屬性我們R.sytleable.MyView_textColor,獲取方法中後面通常設定默認值(float textSize=a.getDimension(R.styleable.MyView_textSize,36);),防止我們在xml文件中沒有定義.從而使用默認值!

獲取,MyView就是定義在<declare-styleable name="MyView"></declare-styleable>裡的名字,獲取裡面屬性用名字_屬性連接起來就可以.TypedArray通常最後調用.recycle()方法,為了保持以後使用該屬性一致性!
MyView.java全部代碼如下:

package com.android.tutor;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.view.View;
public class MyViewe xtends View{
private Paint mPaint;
private Context mContext;
private static final String mString="Welcome";
public MyView(Context context){
super(context);
mPaint=new Paint();
}
public MyView(Context context,AttributeSet attrs){
super(context,attrs);
mPaint=new Paint();
TypedArray a=context.obtainStyledAttributes(attrs,R.styleable.MyView);
int textColor=a.getColor(R.styleable.MyView_textColor,0XFFFFFFFF);
float textSize=a.getDimension(R.styleable.MyView_textSize,36);
mPaint.setTextSize(textSize);
mPaint.setColor(textColor);
a.recycle();
}
@Override
protected void onDraw(Canvas canvas){
//TODOAuto-generatedmethodstub
super.onDraw(canvas);
//設置填充
mPaint.setStyle(Style.FILL);
//畫一個矩形,前倆個是矩形左上角坐標,後面倆個是右下角坐標
canvas.drawRect(newRect(10,10,100,100),mPaint);
mPaint.setColor(Color.BLUE);
//繪制文字
canvas.drawText(mString,10,110,mPaint);
}
}


第三步:將我們自定義的MyView加入布局main.xml文件中,平且使用自定義屬性,自定義屬性
必須加上:
main.xml全部代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:test="http://schemas.android.com/apk/res/com.android.tutor"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"/>
<com.android.tutor.MyView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
test:textSize="20px"
test:textColor="#ffffff"/>
</LinearLayout>

好了,授之以漁。

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved