我正在尝试使用圆角(以及选择的背景颜色)创建一个可以重复使用不同背景颜色的视图;很难解释,所以这是我的代码:
/app/src/com/packagename/whatever/CustomDrawableView.java@H_404_3@
- package com.packagename.whatever;
- import android.content.Context;
- import android.content.res.TypedArray;
- import android.graphics.Canvas;
- import android.graphics.drawable.PaintDrawable;
- import android.util.AttributeSet;
- import android.view.View;
- public class CustomDrawableView extends View {
- private PaintDrawable mDrawable;
- int radius;
- private void init(AttributeSet attrs) {
- TypedArray a = getContext().obtainStyledAttributes(attrs,R.styleable.RoundedRect);
- radius = a.getInteger(R.styleable.RoundedRect_radius,0);
- }
- public CustomDrawableView(Context context,AttributeSet attrs) {
- super(context,attrs);
- init(attrs);
- mDrawable = new PaintDrawable();
- }
- protected void onDraw(Canvas canvas) {
- mDrawable.setCornerRadius(radius);
- mDrawable.draw(canvas);
- }
- }
这是显示自定义组件的XML:
/app/res/layout/test.xml@H_404_3@
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:ny="http://schemas.android.com/apk/res/com.packagename.whatever"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:background="#ffffff"
- android:padding="10dp">
- <com.packagename.whatever.CustomDrawableView
- android:id="@+id/custom"
- android:layout_width="200dp"
- android:layout_height="200dp"
- android:background="#b80010"
- ny:radius="50"
- />
- </LinearLayout>
我想要红色的盒子有50px的圆角,但正如你所看到的,它不会:@H_404_3@
我的想法是,我可以轻松地更改XML中的背景颜色,并自动拥有一个带圆角的漂亮视图,而无需创建多个drawable.@H_404_3@
谢谢您的帮助!@H_404_3@
解决方法
您需要将角半径和颜色设置为背景可绘制.
这是一种可行的方法.抓住你在android:background中设置的颜色,然后用它来创建一个你在构造函数中设置为背景的新drawable.只要您将android:background设置为颜色值,这将起作用.@H_404_3@
- public CustomDrawableView(Context context,attrs);
- init(attrs);
- // pull out the background color
- int color = attrs.getAttributeIntValue("http://schemas.android.com/apk/res/android","background",0xffffffff);
- // create a new background drawable,set the color and radius and set it in place
- mDrawable = new PaintDrawable();
- mDrawable.getPaint().setColor(color);
- mDrawable.setCornerRadius(radius);
- setBackgroundDrawable(mDrawable);
- }