具有圆角的Android自定义组件视图

前端之家收集整理的这篇文章主要介绍了具有圆角的Android自定义组件视图前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用圆角(以及选择的背景颜色)创建一个可以重复使用不同背景颜色的视图;很难解释,所以这是我的代码

/app/src/com/packagename/whatever/CustomDrawableView.java@H_404_3@

  1. package com.packagename.whatever;
  2.  
  3. import android.content.Context;
  4. import android.content.res.TypedArray;
  5. import android.graphics.Canvas;
  6. import android.graphics.drawable.PaintDrawable;
  7. import android.util.AttributeSet;
  8. import android.view.View;
  9.  
  10. public class CustomDrawableView extends View {
  11. private PaintDrawable mDrawable;
  12. int radius;
  13.  
  14. private void init(AttributeSet attrs) {
  15. TypedArray a = getContext().obtainStyledAttributes(attrs,R.styleable.RoundedRect);
  16. radius = a.getInteger(R.styleable.RoundedRect_radius,0);
  17. }
  18.  
  19. public CustomDrawableView(Context context,AttributeSet attrs) {
  20. super(context,attrs);
  21. init(attrs);
  22.  
  23. mDrawable = new PaintDrawable();
  24. }
  25.  
  26. protected void onDraw(Canvas canvas) {
  27. mDrawable.setCornerRadius(radius);
  28. mDrawable.draw(canvas);
  29. }
  30. }

这是显示自定义组件的XML:
/app/res/layout/test.xml@H_404_3@

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:ny="http://schemas.android.com/apk/res/com.packagename.whatever"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. android:background="#ffffff"
  7. android:padding="10dp">
  8.  
  9. <com.packagename.whatever.CustomDrawableView
  10. android:id="@+id/custom"
  11. android:layout_width="200dp"
  12. android:layout_height="200dp"
  13. android:background="#b80010"
  14. ny:radius="50"
  15. />
  16.  
  17. </LinearLayout>

我想要红色的盒子有50px的圆角,但正如你所看到的,它不会:@H_404_3@

我的想法是,我可以轻松地更改XML中的背景颜色,并自动拥有一个带圆角的漂亮视图,而无需创建多个drawable.@H_404_3@

谢谢您的帮助!@H_404_3@

解决方法

您需要将角半径和颜色设置为背景可绘制.

这是一种可行的方法.抓住你在android:background中设置的颜色,然后用它来创建一个你在构造函数中设置为背景的新drawable.只要您将android:background设置为颜色值,这将起作用.@H_404_3@

  1. public CustomDrawableView(Context context,attrs);
  2. init(attrs);
  3.  
  4. // pull out the background color
  5. int color = attrs.getAttributeIntValue("http://schemas.android.com/apk/res/android","background",0xffffffff);
  6.  
  7. // create a new background drawable,set the color and radius and set it in place
  8. mDrawable = new PaintDrawable();
  9. mDrawable.getPaint().setColor(color);
  10. mDrawable.setCornerRadius(radius);
  11. setBackgroundDrawable(mDrawable);
  12. }

如果覆盖onDraw,请确保首先调用super.onDraw(canvas)以获取背景.@H_404_3@

猜你在找的Android相关文章