Android 点击按钮实现来回切换背景图和文字

昨天在做项目的时候碰到了一个见过但没做过的小功能,“点击按钮实现来回切换背景图和文字”  ,虽然很简单,但我还还是想写下来记录自己的成长脚印(本人新手)

如下图,背景图片在绿色和灰色中切换,文字在“已行动”和“未行动”中切换,


我用了两种大同小异的方法

TextView run_action;

run_action = (TextView) findViewById(R.id.fitting_action_run);//跑步

run_action.setOnClickListener(this);

方法一:

定义一个int型变量并且赋初值

public int time = 1;

然后在onClick点击事件里判断即可

if (time % 2 == 1) {
run_action.setBackgroundResource(R.drawable.bg_fitting_action_down);
run_action.setText("已行动");

}else {
run_action.setBackgroundResource(R.drawable.bg_fitting_add);
run_action.setText("未行动");
}


time++;

方法二:

定义一个boolean型变量

boolean isActive;

然后在onClick点击事件里判断:

if (isActive) {
isActive = false;
run_action.setBackgroundResource(R.drawable.bg_fitting_add);
run_action.setText("未行动");
}else{
isActive = true;
run_action.setBackgroundResource(R.drawable.bg_fitting_action_down);
run_action.setText("已行动");
}



你可能感兴趣的:(Android开发)