安卓:从片段中调用活动

14

我正在使用 Activity 中的片段(Fragment)。我在使用 MediaRecorder 进行音频录制。 Activity 有两部分。 第一部分是本身 Activity,用于列出已记录的文件。 在其右侧,当选择录制新文件时,调用 AudioRecording Activity。 当选中列表中的任何文件时,使用 AudioPlayer 播放所录制的文件。 我已经成功地将 Activity 转换为片段,但是当我按下“停止”按钮时,应用程序会终止。

请问是否有人可以回答? 当我将它作为简单 Activity 使用时,我的 audiorecorder 可以正常工作。 是否有类似的解决方案,例如在片段中调用该活动之类的东西? 如果有人知道,请帮帮我。


从片段调用另一个活动使用以下方式: - SubbaReddy PolamReddy
7个回答

35

使用getActivity()获取父Activity,然后像平常一样操作。

Intent myIntent = new Intent(getActivity().getapplicationcontext(), BookmarkActivity.class);
getActivity().startActivity(myIntent); 

10

这里是另一种替代方法。这对我起作用了。

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;
        }
    }

非常感谢,这正是我正在寻找的... ;) - Parthiban M

3
fragment调用另一个activity,请使用以下代码:
Intent i = new Intent(getActivity(), Activity.class);
startActivity(i);

2

您只需要简单地调用

startActivity(new Intent(getActivity(),TheNextActivity.class));

1
在Fragment类中。
 getActivity().startActivity(new Intent(gwtActivity(),MainActivity.class));
 getActivity().finish();

0

你的代码片段应该有一个父元素

Intent intent = new Intent(getActivity(), SecondActivity.class);
getActivity().startActivity(intent);  

0

从Fragment类中调用Activity的最佳方法是在Fragment中创建接口,并在该接口中添加onItemClick()方法。现在将其实现到您的第一个Activity中,然后从那里调用第二个Activity。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接