令牌“OnClickListener”上的语法错误,=此令牌后的预期值

时间:2013-10-05 08:55:31

标签: java android eclipse button onclicklistener

这是我的代码,Eclipse说

Multiple markers at this line
    - Syntax error on token(s), misplaced construct(s)
    - Syntax error on token "OnClickListener", = expected after this token

我不知道该怎么做,谢谢

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.view.View.OnClickListener;



public class MainActivity extends Activity {



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

Button btn = (Button) findViewById(R.id.btn);
btn.OnClickListener (new OnClickListener()
);

    public void onClick(View arg0)
    {
    }

;

}

4 个答案:

答案 0 :(得分:1)

您设置OnClickListener的语法错误。正确的语法是

btn.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) { // You override the onClick method here and this should be within your anonymous OnClickListener class.
        // Code for what happens on click of the button goes here.
    }
});

答案 1 :(得分:1)

// try this
public class MainActivity extends Activity {

    Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               // write your button click code here
           }
       });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

答案 2 :(得分:0)

你的语法错了,试试这个:

btn.setOnClickListener (new OnClickListener(){

    @Override
    public void onClick(View arg0){
    }

});

OnClickListener用作匿名类。你必须在大括号中覆盖onClick。

答案 3 :(得分:0)

试试这个,

 btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            //do your stuff


        }
    });