简体   繁体   English

更改单击时按钮的背景颜色,然后打开一个新活动

[英]Change background color of button on click and then open a new activity

I am trying to make a Button change its background color and launch a new activity on click. 我正在尝试使Button更改其背景颜色,并在单击时启动新的活动。 Below is the code I wrote, but I am getting error message saying to declare 'Button btn1' as 'final Button btn1'. 下面是我编写的代码,但是我收到一条错误消息,要求将“ Button btn1”声明为“ final Button btn1”。 If I do that, the button change its color on click and launch another activity as I wished, but if returning to Main activity from the new activity, the once changed background color stays permanently. 如果这样做,该按钮将在单击时更改其颜色,并根据需要启动另一个活动,但是如果从新活动返回到主活动,则曾经更改过的背景颜色将永久保留。 How can I improve my code? 如何改善我的代码? Thank you. 谢谢。

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);
}
});

只需使用onClick方法的v参数更改所单击的Button背景的颜色,就无需使btn1 final

v.setBackgroundColor(Color.GRAY);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM