【问题标题】:Android : Calling Activity from FragmentAndroid:从片段调用活动
【发布时间】:2012-09-20 04:50:42
【问题描述】:
我在活动中使用片段。我正在使用 MediaRecorder 进行录音。
我有一个活动的两个部分。
第一个本身将列出记录文件的活动。
在它的右侧,当一个选择要为新文件录制时,调用查找活动。
When the any of the listed file is selected i am using AudioPlayer as to play the recorded file.
我在这里能够将 Activity 转换为片段,但是当我按下 Stop 时,它正在终止应用程序。
请任何人都可以回答。当我将它用作简单的活动时,我的录音机工作正常。
任何解决方案,例如我是否可以在该片段中调用该活动或类似的东西。?
如果有人知道,请帮助我。
【问题讨论】:
标签:
android
android-intent
android-fragments
android-audiomanager
android-mediarecorder
【解决方案1】:
使用 get activity 获取父 Activity,然后照常进行。
Intent myIntent = new Intent(getActivity().getapplicationcontext(), BookmarkActivity.class);
getActivity().startActivity(myIntent);
【解决方案2】:
这是另一种替代方法。这对我有用。
public class **YourFragmentClass** extends Fragment {
Context context; //Declare the variable context
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Pass your layout xml to the inflater and assign it to rootView.
View rootView = inflater.inflate(R.layout.**yourfragmentxml**, container, false);
context = rootView.getContext(); // Assign your rootView to context
Button **yourButton** = (Button) rootView.findViewById(R.id.**your_button_id**);
**yourButton**.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Pass the context and the Activity class you need to open from the Fragment Class, to the Intent
Intent intent = new Intent(context, **YourActivityClass**.class);
startActivity(intent);
}
});
return rootView;
}
}
【解决方案3】:
要从fragment 调用另一个activity,请使用:
Intent i = new Intent(getActivity(), Activity.class);
startActivity(i);
【解决方案4】:
您可以简单地调用
startActivity(new Intent(getActivity(),TheNextActivity.class));
【解决方案5】:
在片段类中
getActivity().startActivity(new Intent(gwtActivity(),MainActivity.class));
getActivity().finish();
【解决方案6】:
你的片段应该有一个父级
Intent intent = new Intent(getActivity(), SecondActivity.class);
getActivity().startActivity(intent);
【解决方案7】:
从 Fragment 类调用 Activity 的最佳方式是在 Fragment 中创建接口并在该接口中添加onItemClick() 方法。现在将它实施到您的第一个活动并从那里调用第二个活动。