我想创建一个按钮,它在第一次按下时变红,然后在第二次变回正常灰色(并执行一些操作,如删除文件)。这是为了确认用户真的想要开始删除操作。更改可绘制时,Android按钮仍然处于按下状态
为此,我将背景可绘制更改为具有默认可绘制顶部的额外ColorDrawable的LayerDrawable。根据状态将ColorDrawable的alpha值设置为0或255。
在第一次点击时切换为红色,但第二次点击该按钮会变成黄色,如同按下状态,同时应该恢复为正常灰色。
演示代码:
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();
}
});
}
}
我不想让它看起来像一个切换按钮(因为它不打开和关闭某些东西),所以我需要让它看起来像一个普通的按钮,通过正常按钮的可绘制资源。由于这些资源在不同的Android版本(和不同的设备制造商)之间可能会有所不同,甚至连他们的名字似乎都没有标准化,所以这会变得复杂(可能我忽略了一些东西) –
我编辑了答案检查是否可以帮助您 – Ravi
和为按钮背景创建9个补丁图像 – Ravi