Reputation: 33
I'm just starting out with Android and am working my way through a cookbook and trying out code. My problem is that every time I try to use setOnClickListener I get two syntax errors; one above where the code is going and another at the end of the class. I have copied the code out exactly from the book but am still getting the error. I have tried Google searching, but nobody else seems to have the same problem so I am either doing something wrong or there is a bug in Eclipse.
package com.example.tes;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
Button startButton = (Button) findViewById(R.id.trigger);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
}
});
}
The errors appear on lines 21 - "Syntax error on token "}", delete this token
" and "Syntax error, insert "}" to complete ClassBody
". There are no errors when I add only the "startButton.setOnClickListener" code and they only appear when I try to set the onClickListener.
I am sure I have made an error somewhere, but I honestly can't see it.
Any help would be greatly appreciated.
Thanks.
Upvotes: 1
Views: 2082
Reputation: 82583
You're getting an error because your code is floating in the middle of nowhere, and isn't inside a method. Try using:
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startButton = (Button) findViewById(R.id.trigger);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Upvotes: 7