0

最初に押すと赤くなり、2番目に通常の灰色に戻るボタンを作成したい(そしてファイルの削除などのアクションを実行する)。これは、ユーザーが本当に削除アクションを開始したいかどうかを確認するためのものです。

これを行うには、デフォルトのドローアブルの上に追加の ColorDrawable を使用して、背景のドローアブルを LayerDrawable に変更します。ColorDrawable のアルファは、状態に応じて 0 または 255 に設定されます。

最初のクリックで赤に切り替えると機能しますが、2 回目のクリックでボタンが押された状態のように黄色になり、通常の灰色に戻ります。

デモコード:

package com.example.test;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class TestActivity extends Activity {

    Button button;
    boolean showRed;
    ColorDrawable cd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        button = new Button(this);
        button.setText("Delete");

        // Following two lines don't matter, focus isn't the problem
        button.setFocusable(false);
        button.setFocusableInTouchMode(false);

        cd = new ColorDrawable(0xffff0000);
        cd.setAlpha(0);

        button.setBackgroundDrawable(new LayerDrawable(new Drawable[] {
                button.getBackground(), cd}));

        setContentView(button);


        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                showRed = !showRed;

                if (showRed)
                    cd.setAlpha(255);
                else
                    cd.setAlpha(0);

                // Following line doesn't matter
                button.setSelected(false);

                button.getBackground().invalidateSelf();
            }
        });
    }
}
4

3 に答える 3

0

あなたが達成しようとしていることは、通常のボタンの代わりにトグルボタンを使用して背景を与えることで簡単に実行できると思います。

トグル ボタンは、最初のクリックと 2 番目のクリックの問題を処理できます。

私が言っているのは、通常のボタンの代わりにトグルスイッチを使用し、状況に応じて2つのことを行うことができるということです:

1.> トグル ボタンの背景を、さまざまな状態 (押された、フォーカスされた、デフォルトなど) の色を処理するセレクター xml ファイルに割り当てます。状態については、開発者サイトのドキュメントを確認してください。

2.>背景にデフォルトの色を与えることができます。次にできることは、トグルのチェックされた機能とチェックされていない機能の色を変更することです。

私がトグル ボタンを提案した唯一の理由は、最初のクリックと 2 番目のクリックのオプションを簡単に処理できることです。

また、トグル ボタンの背景をデフォルトから任意の色またはドローアブルに変更するとすぐに、スイッチのように表示されなくなります。textOn 属性と textOff 属性を空白のままにして、オンとオフの記述を削除することもできます。

<ToggleButton
    android:id="@+id/toggleButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/textView1"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="42dp"
    android:text="ToggleButton"
    android:background="@android:color/white"
    android:textOn=""
    android:textOff="" />
于 2013-05-30T10:39:52.037 に答える