如何在网格视图中使用此代码播放音频

时间:2011-03-28 19:05:14

标签: android

我一直在andriod开发者网站上关注此代码。此代码以网格显示图片。我现在要做的是每次用户点击图像时都要玩不同的游戏。我怎么能这样做?

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));

gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
//
Intent myIntent = null;
if(position==0){
//Play some sound...
//MediaPlayer sound= MediaPlayer.create(this,R.raw.alif);
// sound.start();

}
if(position==1){

Toast.makeText(Test.this, "" + "Baa",Toast.LENGTH_SHORT).show();
//Want to play sound here
}
}

});
}

当我添加此代码时:我收到编译错误

  

MediaPlayer类型中的方法create(Context,int)不适用于参数(new AdapterView.OnItemClickListener(){},int)

if(position==0){
    MediaPlayer sound= MediaPlayer.create(this,R.raw.alif);
    sound.start();
}

2 个答案:

答案 0 :(得分:0)

        button.setOnClickListener(
            new View.OnClickListener()
            {
                @Override
                public void onClick(View v) 
                {
                    if ( mPlayer == null ) mPlayer = new MediaPlayer();
                    else mPlayer.stop();


                    try 
                    {
                        mPlayer.setVolume( (float)0.25 * n, (float)0.25 * n );
                        mPlayer.reset();

 // in here your sounds would be listed in an array - pick a random file each time.
                        mPlayer.setDataSource( strSoundFile );
                        mPlayer.prepare();
                        mPlayer.start();
                    } 
                    catch (IllegalArgumentException e) 
                    {

                        myViewUpdateHandler.sendMessage( msg );

                        e.printStackTrace();
                    } catch (IllegalStateException e) 
                    {
                        myViewUpdateHandler.sendMessage( msg );

                        e.printStackTrace();
                    } catch (IOException e) 
                    {
                        myViewUpdateHandler.sendMessage( msg );

                        e.printStackTrace();
                    }

                }
            });   

答案 1 :(得分:0)

final MediaPlayer sound= MediaPlayer.create(this,R.raw.alif);

Intent myIntent = null;
if(position==0){  sound.start();}