更改按钮的OnClickListener时出现匿名类错误

时间:2016-02-13 17:14:17

标签: android onclicklistener

我想在我的Android应用程序中更改按钮的操作,当我编写此代码时,会出现匿名类错误,我不知道为什么。你能帮帮我吗? 错误是:

  

View.OnClickListener是一个匿名类

代码是:

color_Button.setOnClickListener(new View.OnClickListener(){
   public void old_background(View v_1) {
     if (v_1.getId() == R.id.button2) {        
        RelativeLayout background = (RelativeLayout) findViewById(R.id.bg);
        ImageButton newButton = (ImageButton)findViewById(R.id.imageButton);
        Button color_Button = (Button) findViewById(R.id.button2);
        EditText newUsername = (EditText) findViewById(R.id.KidUname);
        background.setBackgroundResource(R.drawable.dora);
        newButton.setImageResource(R.drawable.flower_2);
        color_Button.setBackgroundResource(R.drawable.circle_button);
        color_Button.setText("Diego !!");
        color_Button.setTextColor(Color.parseColor("#FFFFFFFF"));
        newUsername.setHint("Click the flower");
     }
   }
});

1 个答案:

答案 0 :(得分:2)

onClick()内单击按钮时,您应该编写所有必须执行的代码。在您的代码中,您遗漏了onClick(),因此您收到了错误。

根据docs

  单击视图后会调用

onClick()

color_Button.setOnClickListener(new View.OnClickListener(){
       public void onClick(View v_1) {
            if (v_1.getId() == R.id.button2) {
               RelativeLayout background = (RelativeLayout) findViewById(R.id.bg);
               ImageButton newButton = (ImageButton)findViewById(R.id.imageButton);
               Button color_Button = (Button) findViewById(R.id.button2);
               EditText newUsername = (EditText) findViewById(R.id.KidUname);
               background.setBackgroundResource(R.drawable.dora);
               newButton.setImageResource(R.drawable.flower_2);
               color_Button.setBackgroundResource(R.drawable.circle_button);
               color_Button.setText("Diego !!");
               color_Button.setTextColor(Color.parseColor("#FFFFFFFF"));
               newUsername.setHint("Click the flower");
            }
        }
});