Java 无法手动更改按钮的颜色

Java 无法手动更改按钮的颜色,java,android,eclipse,button,Java,Android,Eclipse,Button,我有以下代码: Button x = (Button) findViewById(R.id.button1); x.setBackgroundColor(Color.BLACK); 我在setBackgroundColor行上得到以下错误: Syntax error on token "setBackgroundColor", Identifier expected after this token 我正在尝试手动更改颜色代码,因为这取决于用户是否单击了按钮 我有一个id为“button1

我有以下代码:

Button x = (Button) findViewById(R.id.button1);
x.setBackgroundColor(Color.BLACK);
我在setBackgroundColor行上得到以下错误:

Syntax error on token "setBackgroundColor", Identifier expected after this token
我正在尝试手动更改颜色代码,因为这取决于用户是否单击了按钮

  • 我有一个id为“button1”的按钮

谢谢

试试这段代码,它会起作用:

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

尝试此代码,它将工作:

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

我认为您已经将此代码写在了无法正确执行的方法之外。您需要将此代码移到某个方法中

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

我认为您已经将此代码写在了无法正确执行的方法之外。您需要将此代码移到某个方法中

 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);
    }
    }
使用此代码:

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

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

Button x = (Button) findViewById(R.id.button1);
x.setBackgroundColor(Color.BLACK);
必须工作。。。。但是既然你越来越

Syntax error on token "setBackgroundColor", Identifier expected after this token
这意味着您的语句在任何方法之外,但在类块内部。不能将语句直接放入类声明中。你需要把它们放在方法中。。正如@Mukesh Kumar正确指出的那样

您的代码

Button x = (Button) findViewById(R.id.button1);
x.setBackgroundColor(Color.BLACK);
必须工作。。。。但是既然你越来越

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

这意味着您的语句在任何方法之外,但在类块内部。不能将语句直接放入类声明中。你需要把它们放在方法中。。正如@Mukesh Kumar正确指出的那样

你能发布更多的活动代码吗???你能发布更多的活动代码吗???你是对的!我已经把它放在一个方法中,现在它可以工作了!谢谢!你说得对!我已经把它放在一个方法中,现在它可以工作了!谢谢!