【发布时间】:2016-01-21 19:02:33
【问题描述】:
我有一个按钮,如果你按住手机会振动,如果超过 1.5 秒就会改变背景颜色。 但我希望在按下第一个按钮时将颜色变为绿色,如果第二次按下则变为红色,以此类推。
我的代码:
public class MainActivity extends Activity {
public static int MILISEGUNDOS_ESPERA = 1500;
private RelativeLayout mealLayout;
private ToggleButton toggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mealLayout = (RelativeLayout) findViewById(R.id.layout);
final Vibrator vibrator;
vibrator = (Vibrator) getSystemService(MainActivity.VIBRATOR_SERVICE);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
esperarYCerrar(MILISEGUNDOS_ESPERA);
if (action == MotionEvent.ACTION_DOWN) {
vibrator.vibrate(1500);
} else if (action == MotionEvent.ACTION_UP) {
vibrator.cancel();
}
return true;
}
});
}
public void esperarYCerrar(int milisegundos) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
// acciones que se ejecutan tras los milisegundos
finalizarApp();
cambiarcolor();
}
}, milisegundos);
}
/**
* Finaliza la aplicación
*/
public void finalizarApp() {
mealLayout.setBackgroundColor(Color.RED);
}
public void cambiarcolor() {
ToggleButton button=(ToggleButton) findViewById(R.id.button1);
if (button.isChecked())
mealLayout.setBackgroundColor(Color.GREEN);
else
mealLayout.setBackgroundColor(Color.RED);
}
}
问题是这两种颜色都不起作用,只起作用一种颜色,我想知道如何让你每次按下按钮时都放一种不同的颜色,红色和绿色。
【问题讨论】:
-
好吧,它就是这么做的。但问题是什么?
-
stackoverflow.com/a/2895650/5456493 告诉它是否工作?
-
你想改变点击按钮的背景吗?
-
问题是这两种颜色都不起作用,只起作用一种颜色,我想知道如何让你每次按下按钮都放一种不同的颜色,红色和绿色。
-
颜色没有变化是你的问题吗?或者你想改变颜色,否则不起作用?
标签: android background