自定义视图的尺寸,包含可绘制的形状

时间:2011-12-23 18:27:23

标签: android layout custom-controls drawable

我几乎关注了http://developer.android.com/guide/topics/graphics/2d-graphics.html#shape-drawable

中的示例
  public class CustomDrawableView extends View {

  private ShapeDrawable mDrawable;

  public CustomDrawableView(Context context, AttributeSet attr) {
  super(context, attr);

  int x = 10;
  int y = 10;
  int width = 300;
  int height = 50;

  mDrawable = new ShapeDrawable(new OvalShape());
  mDrawable.getPaint().setColor(0xff74AC23);
  mDrawable.setBounds(x, y, x + width, y + height);
  }

  protected void onDraw(Canvas canvas) {
  mDrawable.draw(canvas);
  }
  }

  // XML snippet where I am using this custom view
  <com.example.shapedrawable.CustomDrawableView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"/>

我实际上是在ListView中使用它,所以它在我的Adapter的getView方法中被夸大了(我知道这可行,因为它看起来很适合非自定义视图)。

我注意到除非我为layout_width和layout_height指定“dp”值,否则它不会绘制。但是,如果我使用500dp之类的任意内容来布局layout_width和layout_height,那么它就会出现! 我很困惑 - 为什么不使用我在使用wrap_content时在代码中指定的高度/宽度尺寸?

1 个答案:

答案 0 :(得分:1)

事实证明我必须覆盖onMeasure并返回我的drawable的测量值。我使用LabelView APIDemo作为示例。