1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > android 自定义控件 attrs android 使用attrs自定义控件

android 自定义控件 attrs android 使用attrs自定义控件

时间:2023-07-21 22:00:09

相关推荐

android 自定义控件 attrs android 使用attrs自定义控件

步骤:

1、在values下新建一个attrs.xml的资源文件(my_attrs.xml)

//===》name为引用资源的名称

// attr中的 name为自定义的名称 format 为类型

// 字体颜色

//字体大小

//字符串

2、新建一个类MyAttrsMyView继承 View

覆写public MyAttrsMyView(Context context, AttributeSet attrs)方法

@SuppressLint("NewApi")

public MyAttrsMyView(Context context, AttributeSet attrs) {

super(context, attrs);

// TODO Auto-generated constructor stub

mPaint = new Paint(); //定义画笔

imageView = new ImageView(context); //图片

imageView.setImageResource(R.drawable.ww); //加载图片资源

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.My_attrs);//获取自定义的attrs中的资源

float textsize = a.getDimension(R.styleable.My_attrs_TextSize, 40);

int c = a.getColor(R.styleable.My_attrs_TextColor, 0x990000FF);

s = a.getString(R.styleable.My_attrs_Text);

mPaint.setColor(c);

mPaint.setTextSize(textsize);

a.recycle();//结束标记

}

@Override

protected void onDraw(Canvas canvas) {

// TODO Auto-generated method stub

super.onDraw(canvas);

//canvas.drawRect(new Rect(10, 10, 280, 200), mPaint);

//((BitmapDrawable)imageView.getDrawable()).getBitmap() ;将imageview转换成bitmap

canvas.drawBitmap(((BitmapDrawable)imageView.getDrawable()).getBitmap(), 1, 20, mPaint);

//canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ww), 10, 10, mPaint);

canvas.drawText(s, 1, 100, mPaint);

}

3、最后一步

第一种写法 在activity中 , 直接new出自定义的类即可

MyView = new MyAttrsMyView(this,null);

setContentView(MyView);

第二种写法 利用xml

1、在xml中

2、在其根布局 添加声明 : xmlns:ymy(自己起的名)="/apk/res/项目的主包名"

3、给自定义的控件中添加attrs 中定义好的属性 : ymy:Text = "顺丰快递"

xmlns:ymy="/apk/res/com.ming"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical" >

android:layout_width="400dp"

android:layout_height="300dp"

ymy:TextColor = "#ABCDEFEF" ymy:Text = "顺丰快递" ymy:TextSize = "12sp" />

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。