【问题标题】:Change background color of button on click and then open a new activity单击时更改按钮的背景颜色,然后打开一个新活动
【发布时间】:2015-05-01 06:37:06
【问题描述】:

我正在尝试使按钮更改其背景颜色并在单击时启动新活动。下面是我编写的代码,但我收到错误消息,提示将“Button btn1”声明为“final Button btn1”。如果我这样做,按钮会在单击时更改其颜色并按我的意愿启动另一个活动,但如果从新活动返回主活动,则曾经更改过的背景颜色将永久保留。如何改进我的代码?谢谢。

public class Home extends ActionBarActivity{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_home);

Button btn1 = (Button) findViewById(R.id.button);

btn1.setOnClickListener(new View.OnClickListener(){

@Override
public void onClick(View v) {

   btn1.setBackgroundColor(Color.GRAY);

   Intent intent = new Intent(v.getContext(), activity_street.class);
   startActivityForResult(intent, 0);
}
});

【问题讨论】:

  • 你只是想在按下按钮时显示另一种颜色然后它就消失了吗??
  • 是的,我想显示按钮被点击了。现在它在更改为“v.setBackgroundColor”后工作正常。

标签: java android button background-color final


【解决方案1】:

不需要btn1 final 只需使用onClick 方法的v 参数来改变点击按钮背景的颜色:

v.setBackgroundColor(Color.GRAY);

【讨论】:

    猜你喜欢
    • 2015-05-14
    • 2015-01-26
    • 2014-10-09
    • 2017-08-02
    • 2014-10-10
    • 2022-11-13
    • 2017-01-26
    • 2013-06-05
    相关资源
    最近更新 更多