3

StateListDrawableライブラリ プロジェクトのカスタム ビューの背景としてプログラムで a を設定しようとしています。これが私がやっていることです:

final TypedArray a = getContext().obtainStyledAttributes(attrs,
            R.styleable.ActionBar);
    int firstColor = a.getColor(
            R.styleable.ActionBar_backgroundGradientFirstColor, 0xff000000);
    int secondColor = a
            .getColor(R.styleable.ActionBar_backgroundGradientSecondColor,
                    0xff000000);
    int textViewColor = a.getColor(R.styleable.ActionBar_titleColor,
            0xffffffff);
    int onClickColor = a.getColor(
            R.styleable.ActionBar_backgroundClickedColor, 0xff999999);
    a.recycle();

    StateListDrawable sld = new StateListDrawable();
    GradientDrawable drawable = new GradientDrawable(
            Orientation.TOP_BOTTOM, new int[] { firstColor, secondColor });
    sld.addState(new int[] { android.R.attr.state_enabled },
            new ColorDrawable(onClickColor));
    sld.addState(new int[] { android.R.attr.state_pressed }, drawable);

    action2.setBackgroundDrawable(sld);
    action3.setBackgroundDrawable(sld);
    actionBack.setBackgroundDrawable(sld);
    pb.setBackgroundDrawable(drawable);
    tv.setBackgroundDrawable(drawable);
    tv.setTextColor(textViewColor);

ただし、これは機能していません。常に有効な状態を描画します。ボタンを押したときに押された状態を描画したい。私は何を間違っていますか?

4

1 に答える 1

20

ボタンが押されている間、ボタンはまだ有効になっていると思いますか?

順序を逆にしてみてください。

sld.addState(new int[] { android.R.attr.state_pressed }, drawable);
sld.addState(new int[] { android.R.attr.state_enabled },
        new ColorDrawable(onClickColor));

おそらく、現在有効な最初の状態が描画されています。

押されているときに別の背景が必要な場合、および他のすべての場合に別の背景が必要な場合は、次を使用することもできます。

sld.addState(new int[] { android.R.attr.state_pressed }, drawable);
sld.addState(new int[] { StateSet.WILD_CARD },
        new ColorDrawable(onClickColor));

追加:これをテストしたところ、次のテストコードが機能します。

Button testButton = new Button(context);
            testButton.setText("Test");
            StateListDrawable sld = new StateListDrawable();
            GradientDrawable drawable = new GradientDrawable(
                    Orientation.TOP_BOTTOM, new int[] { Color.BLUE, Color.RED });
            sld.addState(new int[] { android.R.attr.state_pressed }, drawable);
            sld.addState(StateSet.WILD_CARD, new ColorDrawable(Color.YELLOW));
            testButton.setBackgroundDrawable(sld);          
            mainLayout.addView(testButton);
于 2012-10-05T13:58:08.663 に答える