您的位置:首页 > 移动开发 > Android开发

android-R.styleable(应用)

2016-06-21 15:03 399 查看
res/values 文件下定义一个attrs.xml 文件

<?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下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: