我想在我的sherlock-fragment中启动一个MediaPlayer实例但是上下文不起作用。
我尝试过getContext(),getActivity()和getSherlockActivity()
尝试用isAttached()包围它也不成功。
错误 “对于Fragment_1”
类型,方法isAttached()未定义我的错误在别的地方吗?谢谢。
public class Fragment_1 extends SherlockFragment{
public Button b1;
public Button b2;
public Button b3;
public Button r1;
public Button r2;
public Button s1;
public Button s3;
private static String mFileName = null;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.fragment_1, container, false);
if( isAttached() ) {
final MediaPlayer mp = MediaPlayer.create(getActivity(), R.raw.sechs);
}
View vb1 = inflater.inflate(R.layout.fragment_1, container, false);
b1 = (Button)vb1.findViewById(R.id.play);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View vb1) {
mp.start();
}
});
View vb2 = inflater.inflate(R.layout.fragment_1, container, false);
b2 = (Button)vb2.findViewById(R.id.pause);
b2.setOnClickListener(new OnClickListener() {
public void onClick(View vb2) {
mp.pause();
}
});
}
答案 0 :(得分:0)
在使用getActivity()之前,请检查isAdded()片段方法
答案 1 :(得分:0)
public class Fragment_1 extends SherlockFragment{
public Button b1;
public View view;
public MediaPlayer mp = null;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_1, container, false);
mp = MediaPlayer.create(getActivity(), R.raw.sechs);
Button b1 = (Button) view.findViewById(R.id.play);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mp.start();
}
});
return view;
}
}
答案 2 :(得分:-1)
at" onCreateView"生命周期,片段不附加到活动。 您需要访问" onActivityCreated"。
中的活动@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
/** You can try getActivity() here. it should not be null. **/
}