最初に押すと赤くなり、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();
}
});
}
}