1

我有这个代码:

    hubSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
     public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
      final MediaPlayer mp2 = MediaPlayer.create(Textbox.this, R.raw.hero);
      mp2.start();
        }
        public void onNothingSelected(AdapterView<?> parentView) {
        }
    });

(代码基本上在从微调器中选择一个新项目然后播放歌曲时运行,-稍后将是一个基于所选内容的变量,但我现在很好)

问题:

而且我希望能够在这个公共空白中使用“mp2”,(我想要一个暂停它的按钮)我该怎么做?

请解释/显示...

非常感谢

詹姆士

4

2 回答 2

0

我不确定当你调用时会发生什么MediaPlayer.create(Textbox.this, R.raw.hero),但假设它没有立即影响,你可以在侦听器之外创建对象。


Edit1:好的,那么这个怎么样?

MediaPlayer currentPlayer;

methodA()
{
   hubSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
   {
       public void onItemSelected(AdapterView<?> parentView,
             View selectedItemView, int position, long id)
       {
          MediaPlayer mp2 = MediaPlayer.create(Textbox.this, R.raw.hero);
          mp2.start();
          setPlayer(mp2);
       }
       public void onNothingSelected(AdapterView<?> parentView) {
    }
});


setMediaPlayer(MediaPlayer player)
{
   currentPlayer = player;
}
于 2010-04-21T17:51:25.443 回答
0

将变量移动mp2到父类的实例。这将保持对它的运行引用,您可以随时与之交互。尽管 if将被多次调用并存储,但您将需要删除final限定符。MediaPlayer.create(...)


编辑:

我指的是这样的事情:

class SomeClass {
    private MediaPlayer mp2 = null;

    private void whateverFunctionYouAreIn() {
        hubSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
                SomeClass.this.mp2 = MediaPlayer.create(Textbox.this, R.raw.hero);
                SomeClass.this.mp2.start();
            }
            public void onNothingSelected(AdapterView<?> parentView) {}
        });

        //TODO: put this in an onClickListener:
        if (this.mp2 != null) {
            this.mp2.pause();
        }
    }
}
于 2010-04-21T17:52:56.240 回答