任何人都可以帮我弄清楚我哪里出错了。单击按钮,媒体播放器随机播放其中一个 mfile,我试图根据播放的文件设置 TextView 。目前 setText if 语句仅匹配播放一半时间的音频。真的不确定我哪里出错了。
private final int SOUND_CLIPS = 3;
private int mfile[] = new int[SOUND_CLIPS];
private Random rnd = new Random();
MediaPlayer mpButtonOne;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mfile[0] = R.raw.one;
mfile[1] = R.raw.two;
mfile[2] = R.raw.three;
//Button setup
Button bOne = (Button) findViewById(R.id.button1);
bOne.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final TextView textOne = (TextView)findViewById(R.id.textView1);
mpButtonOne = MediaPlayer.create(MainActivity.this, mfile[rnd.nextInt(SOUND_CLIPS)]);
if (mpButtonOne==null){
//display a Toast message here
return;
}
mpButtonOne.start();
if (mfile[rnd.nextInt(SOUND_CLIPS)] == mfile[0]){
textOne.setText("one");
}
if (mfile[rnd.nextInt(SOUND_CLIPS)] == mfile[1]){
textOne.setText("two");
}
if (mfile[rnd.nextInt(SOUND_CLIPS)] == mfile[2]){
textOne.setText("three");
}
mpButtonOne.setOnCompletionListener(new soundListener1());
{
}
所以澄清一下我遇到的问题是 setText 只是偶尔匹配音频,而不是每次点击时。其余时间它会为错误的音频显示错误的文本。
最佳答案
您正在选择另一个随机文件
mfile[rnd.nextInt(SOUND_CLIPS)]
将其设置为 onClick()
中的变量,然后在 if
语句中检查该变量
public void onClick(View v) {
int song = mfile[rnd.nextInt(SOUND_CLIPS)];
final TextView textOne = (TextView)findViewById(R.id.textView1);
mpButtonOne = MediaPlayer.create(MainActivity.this, song);
if (song == mfile[0]){
textOne.setText("one");
}
编辑
要使其成为成员变量以便您可以在类中的任何地方使用它,只需在方法外部声明它即可。通常在 onCreate()
之前执行此操作,这样所有成员变量都在同一个位置,并使您的代码更具可读性/可管理性。
public class SomeClass extends Activity
{
int song;
public void onCreate()
{
// your code
}
然后你可以在你的onClick()
public void onClick(View v) {
song = mfile[rnd.nextInt(SOUND_CLIPS)];
final TextView textOne = (TextView)findViewById(R.id.textView1);
mpButtonOne = MediaPlayer.create(MainActivity.this, song);
关于java - TextView if 语句不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18749340/