Amit
Amit

Reputation: 703

Cannot change the color of a button manually

I have the following code :

Button x = (Button) findViewById(R.id.button1);
x.setBackgroundColor(Color.BLACK);

and I get the following error on the setBackgroundColor line :

Syntax error on token "setBackgroundColor", Identifier expected after this token

I'm trying to change the color code manualy, as it depends if the user has clicked on the button....

Thanks!

Upvotes: 0

Views: 119

Answers (4)

CRUSADER
CRUSADER

Reputation: 5472

Your code

Button x = (Button) findViewById(R.id.button1);
x.setBackgroundColor(Color.BLACK);

Must work.... but since you are getting

Syntax error on token "setBackgroundColor", Identifier expected after this token

that means your statement is outside any method but inside a class block. You can't put statements into a class declaration directly. you need to put them inside method.. As @Mukesh Kumar rightly pointed.

Upvotes: 1

Naddy
Naddy

Reputation: 2674

use this code:

x.setBackgroundColor(Color.parseColor("#000000"));//you can put hex code of any color inside the quotation.For black hex code is "000000"

Upvotes: 1

Mukesh Kumar Singh
Mukesh Kumar Singh

Reputation: 4532

I think You have written this code out side of method which can not executed properly.You need to move this code inside some method

 public class SpinnerBuilding extends Activity {
    public void onCreate(Bundle state){

    super.onCreate(state);
    setContentView(R.id.layout);
    ...
    Button x = (Button) findViewById(R.id.button1);
    x.setBackgroundColor(Color.BLACK);
    }
    }

Upvotes: 2

amalBit
amalBit

Reputation: 12191

Try this code, it will work:

b.setBackgroundColor(getResources().getColor(R.color.red));

Upvotes: 1

Related Questions