我有这样的代码:
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
MediaPlayer sound1, sound2;
sound1 = MediaPlayer.create(this, R.raw.cows);
sound2 = MediaPlayer.create(this, R.raw.sheep);
final Button button1 = (Button) findViewById(R.id.Button01);
button1.setOnClickListener(this);
final Button button2 = (Button) findViewById(R.id.Button02);
button1.setOnClickListener(this);
public void onClick(View v) {
switch(v.getId()) {
case R.id.Button01:
sound1.start();
break;
case R.id.Button02:
sound2.start();
break;
}
}
protected void onDestroy() {
sound1.release();
sound2.release();
super.onDestroy();
}
}我有一个警告,说按钮和视图不正确。
但是,我不明白上面的代码有什么问题。
似乎我需要实例化button类和View类。
但我不知道该怎么做。
发布于 2014-01-06 01:57:03
这应该在一个方法中
sound1 = MediaPlayer.create(this, R.raw.cows);
sound2 = MediaPlayer.create(this, R.raw.sheep);
final Button button1 = (Button) findViewById(R.id.Button01);
button1.setOnClickListener(this);
final Button button2 = (Button) findViewById(R.id.Button02);
button1.setOnClickListener(this); // should be button2您可以在onCreate中初始化视图
Button button1,button2;
MediaPlayer sound1,sound2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sound1 = MediaPlayer.create(this, R.raw.cows);
sound2 = MediaPlayer.create(this, R.raw.sheep);
button1 = (Button) findViewById(R.id.Button01);
button1.setOnClickListener(this);
button2 = (Button) findViewById(R.id.Button02);
button2.setOnClickListener(this);
}然后
public class MainActivity extends Activity implements onClickListener {发布于 2016-03-17 21:47:23
首先你必须把final Button button1 = (Button) findViewById(R.id.Button01); button1.setOnClickListener(this); final Button button2 = (Button) findViewById(R.id.Button02); button1.setOnClickListener(this);放在onCreate()方法中。
这将自动创建onclick方法。在其中放入切换代码。
希望它能工作,并帮助你解决错误。
发布于 2014-01-06 03:40:14
在“nClick`”方法之上实现View.onClickListener,应该包含@Override表示法
https://stackoverflow.com/questions/20937052
复制相似问题