1

我正在使用 Fragments,但是此代码无法运行。有人可以帮我弄这个吗。代码中的问题似乎与这部分“(start.this”)有关。

public class frag extends FragmentActivity {
public MediaPlayer mp = null;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button b = (Button) findViewById(R.id.button1);
    b.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            if (mp == null) {
            mp = MediaPlayer.create(start.this, R.raw.praise1);
            mp.start();
            }else {
                mp.stop();
                mp = null;
            }   }


    });
    }
  }
4

2 回答 2

0

更改start.this为实际上下文。您可以使用getParent(),也可以在创建之前存储上下文onClickListener并将其传递:

setContentView(R.layout.activity_main);
final Context context = this;

//inside the onClickListener
mp = MediaPlayer.create(context, R.raw.praise1);
于 2012-10-25T03:00:09.667 回答
0

将您的代码更改为

public class frag extends FragmentActivity {
public MediaPlayer mp = null;
 @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        if (mp == null) {
        mp = MediaPlayer.create(getApplicationContext(), R.raw.praise1);//==> Here is the change
        mp.start();
        }else {
            mp.stop();
            mp = null;
        }   }


});
 }
 }
于 2012-10-25T03:19:11.847 回答