我有这个代码:
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();
}
}
我收到一条警告,指出按钮和 View 不正确。
但是,我不明白上面的代码有什么问题。
看来我需要实例化按钮类和 View 类。
但我不知道该怎么做。
最佳答案
这应该在方法内部
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
中初始化 View
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 {
关于java - 按钮点击监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20937052/