我正在阅读一本关于java练习的书,并且已经陷入了这种语法错误。我搜索了onSetClickListener语法错误,并且不认为我在重复问题。 Eclipse说'令牌上的语法错误'setOnClickListener“,此标记之后的标识符'。谢谢你的帮助!
package fifth.example.eventhandling;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener{
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(this); <<ERROR HERE
@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.activity_main, menu);
return true;
}
@Override
public void onClick(View arg0) {
TextView text = (TextView)findViewById(R.id.textmessage);
text.setText("BUTTON HAS BEEN CLICKED. EVENT PROCESSED.");
}
}
答案 0 :(得分:3)
一个问题是:代码中的按钮相关代码应位于onCreate()
内setContentView...
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(this); <<ERROR HERE
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
应该是:
公共类MainActivity扩展Activity实现OnClickListener { 按钮按钮; //声明按钮听到
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(this); <<ERROR HERE
}
}
答案 1 :(得分:2)
目前,您在设置Activity的布局之前尝试初始化按钮。在setContentView
之后的onCreate of Activity中移动按钮初始化为:
public class MainActivity extends Activity implements OnClickListener{
Button button ; //<<< declare button here
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button1); //<<< initilze here
button.setOnClickListener(this);
}
答案 2 :(得分:0)
你的代码应该是这样的。
public class MainActivity extends Activity implements OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(this); <<ERROR 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.activity_main, menu);
return true;
}
@Override
public void onClick(View arg0) {
TextView text = (TextView)findViewById(R.id.textmessage);
text.setText("BUTTON HAS BEEN CLICKED. EVENT PROCESSED.");
}