我正在使用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;
} }
});
}
}
答案 0 :(得分:0)
将start.this
更改为实际上下文。您可以使用getParent()
,也可以在创建onClickListener
之前存储上下文并将其传入:
setContentView(R.layout.activity_main);
final Context context = this;
//inside the onClickListener
mp = MediaPlayer.create(context, R.raw.praise1);
答案 1 :(得分: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;
} }
});
}
}