41
40

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Shape drawableをxmlではなくJavaコードで動的に生成する

Posted at
background_shape.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android">
  <stroke android:width="3dp" android:color="#FF0000FF" />
  <corners android:radius="3dp" />
  <solid android:color="#660000FF" />
</shape>

これと同等なものを動的に生成しようとしてはまる

float[] outerR = new float[] { 3, 3, 3, 3, 3, 3, 3, 3 }; // dp -> px の処理はひとまず置いておく
ShapeDrawable drawable = new ShapeDrawable(new RoundRectShape(outerR, null, null));
drawable.getPaint().setColor(Color.parseColor("#FF0000FF"));
drawable.setSolidColor(Color.parseColor("#660000FF")); // こんなメソッドは無い!!

ドキュメントを読むと、shapeで記述されたxmlはShapeDrawableではなくGradientDrawableへのresource pointerだと書いてあるので、以下が正しい。

GradientDrawable drawable = new GradientDrawable();
drawable.setStroke(3, Color.parseColor("#FF0000FF"));
drawable.setCornerRadius(3);
drawable.setColor(Color.parseColor("#660000FF"));
41
40
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
41
40

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?