简体   繁体   中英

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. Below is the code I wrote, but I am getting error message saying to declare 'Button btn1' as '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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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