0

XMLコードを介してカスタムボタンの背景形状を作成することができました

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="true" >
        <shape android:shape="rectangle"  >
            <corners android:radius="24dp" />
            <stroke android:width="2dp" android:color="@color/colorWhite" />
            <solid android:color="@color/colorPrimary" />
        </shape>
    </item>
    <item android:state_focused="true">
        <shape android:shape="rectangle"  >
            <corners android:radius="24dp" />
            <stroke android:width="2dp" android:color="@color/colorWhite" />
            <solid android:color="@color/colorPrimary" />
        </shape>
    </item>
    <item >
        <shape android:shape="rectangle"  >
            <corners android:radius="24dp" />
            <stroke android:width="2dp" android:color="@color/colorWhite" />
            <solid android:color="@color/colorWhite" />
        </shape>
    </item>
</selector>

しかし、それに相当するJavaコードは何だろう?ガイドをお願いします。

4

2 に答える 2

1

Java でこれを行うと、はるかに冗長になりますが、実行する必要があることは次のとおりです。

  • 作成するnew StateListDrawable()
  • 各状態について:
    • を作成しますnew ShapeDrawable(new RoundRectShape(...))。コンストラクターの引数がどのように機能するか正確には思い出せませんが、実験することはできます。
    • shapeDrawable.getPaint()その Paint オブジェクトを取得して変更するために使用します。setColor()おそらく、setStyle()、および を使用するでしょうsetStrokeWidth()
    • 状態セットを構築します。これは、必要な状態の など、さまざまな Android 状態属性で構成される整数の配列android.R.attr.state_pressedです。
    • コールしstateListDrawable.addState(stateSet, shapeDrawable)ます。StateSet.NOTHINGデフォルト状態には (または空の int[]) を使用できます。XML に表示される順序で追加してください。

このようなもの:

StateListDrawable stateListDrawable = new StateListDrawable();
Shape roundRect = new RoundRectShape(...);
// Add states in order. I'll just demonstrate one.
ShapeDrawable pressed = new ShapeDrawable(roundRect);
Paint paint = pressed.getPaint();
paint.setColor(Color.BLUE);
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(10f); // this is in pixels, you'll have to convert to dp yourself
int[] pressedState = { android.R.attr.state_pressed };
stateListDrawable.addState(pressedState, pressed);
于 2015-12-12T05:17:18.770 に答える