我在Android编程中尝试自己。尝试编写一个由3个图像按钮组成的程序,如果首先单击,音乐播放,显示某个消息,如果第二个按下,则另一个音乐将与另一个消息显示一起播放。但错误信息显示"复制局部变量mp2"在为第二个medialplayer写的编码的第二行。请指导我。
package com.example.imagebutton;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
final MediaPlayer mp1;
final MediaPlayer mp2 = null;
ImageButton ib1 = (ImageButton) findViewById(R.id.imageButton1);
mp1 = MediaPlayer.create(this, R.raw.muzikone);
ib1.setOnClickListener (new View.OnClickListener() {
private MediaPlayer mp3;
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "First Button Pressed!", Toast.LENGTH_LONG).show();
if(mp2.isPlaying()){
mp2.reset();
}else{
mp3.reset();
}
mp1.start();
}
});
ImageButton ib2 = (ImageButton) findViewById(R.id.imageButton2);
final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.muziktwo);
ib2.setOnClickListener (new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Second Button Pressed!", Toast.LENGTH_LONG).show();
if(mp1.isPlaying()){
mp1.reset();
}
mp2.start();
}
});
ImageButton ib3 = (ImageButton) findViewById(R.id.imageButton3);
final MediaPlayer mp3 = MediaPlayer.create(this, R.raw.muzikthree);
ib3.setOnClickListener (new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Third Button Pressed!", Toast.LENGTH_LONG).show();
if(mp1.isPlaying()){
mp1.reset();
}else{
mp2.reset();
}
mp3.start();
}
});
}catch(Exception e) {
}
}
}
答案 0 :(得分:1)
mp2
被声明两次,如下所示:
final MediaPlayer mp2 = null;
在这里
final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.muziktwo);
要解决此问题,请删除其中一个声明。
注意:我认为您的代码中存在严重的范围问题,例如阅读this lesson可能有帮助