【问题标题】:Cannot change the color of a button manually无法手动更改按钮的颜色
【发布时间】:2013-11-15 14:26:50
【问题描述】:

我有以下代码:

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

我在 setBackgroundColor 行收到以下错误:

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

我正在尝试手动更改颜色代码,因为这取决于用户是否单击了按钮......

  • 我确实有一个 ID 为“button1”的按钮

谢谢!

【问题讨论】:

  • 你能发布更多这个活动的代码吗????

标签: java android eclipse button


【解决方案1】:

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

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

【讨论】:

  • 你是对的!我已经把它放在一个方法中,它现在可以工作了!非常感谢!
【解决方案2】:

试试这个代码,它会工作:

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

【讨论】:

    【解决方案3】:

    使用此代码:

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

    【讨论】:

      【解决方案4】:

      你的代码

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

      必须工作....但是既然你得到了

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

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

      【讨论】:

        猜你喜欢
        • 2022-01-22
        • 2023-01-28
        • 2021-06-28
        • 1970-01-01
        • 2019-09-24
        • 2020-09-07
        • 1970-01-01
        • 2020-01-01
        • 1970-01-01
        相关资源
        最近更新 更多