这是我的尝试:按下按钮时会出现一个不同的随机图像(这部分有效)。我不能去工作的是我希望它做的另一部分。取决于出现的图像将取决于播放的声音片段。即,如果图像是一辆黑色汽车,则会播放 2 个单独的文件;一个说黑色,另一个说汽车。任何帮助是极大的赞赏。这是我的代码:
public class Black extends Activity {
ImageView imageView;
MediaPlayer mp;
int sound=525,sound1=525;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.black);
Button Button1 = (Button) findViewById(R.id.button1);
imageView= (ImageView)findViewById(R.id.image1);
Button1.setOnClickListener( new OnClickListener(){
public void onClick(View v){
onClickImageView(v);
}
});
}
public void onClickImageView(View view) {
int[] picture= {
R.drawable.black,R.drawable.blackairplane,R.drawable.blackbear,R.drawable.blackcar,R.drawable.blackcircle,
R.drawable.blackkite,R.drawable.blacksquare,R.drawable.blacktriangle};
Random r = new Random();
int n=r.nextInt(7);
imageView.setImageResource(picture[n]);
switch (picture[n]) {
case R.drawable.black:
sound = R.raw.sayblack;
sound1 = R.raw.sayblack;
break;
case R.drawable.blackairplane:
sound = R.raw.sayblack;
sound1= R.raw.sayairplane;
break;
case R.drawable.blackbear:
sound = R.raw.sayblack;
sound1 = R.raw.saybear;
break;
case R.drawable.blackcar:
sound = R.raw.sayblack;
sound1= R.raw.saycar;
break;
case R.drawable.blackcircle:
sound = R.raw.sayblack;
sound1=R.raw.saycircle;
break;
case R.drawable.blackkite:
sound = R.raw.sayblack;
sound1 = + R.raw.saykite;
break;
case R.drawable.blacksquare:
sound = R.raw.sayblack;
sound1 = R.raw.saysquare;
break;
case R.drawable.blacktriangle:
sound = R.raw.sayblack;
sound1= R.raw.saytriangle;
break;
}
if(mp!=null){
mp.release();
}
if(sound!=0){
mp = MediaPlayer.create(getBaseContext(), sound);
mp.start();
}
mp.setOnCompletionListener (new MediaPlayer.OnCompletionListener(){
@Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
if(sound1!=0 && sound!=0){
mp= MediaPlayer.create(getBaseContext(),sound1);
mp.start();
sound=sound1=525;
}}
});
}
}
这是我的 .xml 文件:
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="40dp"
android:background="@color/white"
android:text="@string/black" />
<ImageView
android:id="@+id/image1"
android:layout_width="320dp"
android:layout_height="250dp"
android:scaleType="fitXY"
android:contentDescription="@string/black" />
...这是正确的代码。