一个片段中开始通过意向片段片段、意向

2023-09-03 21:06:34 作者:逝水无痕

我要推出一个新的片段,来查看一些数据。目前,我有有一堆动作条片,其中每一个是一个片段的主要活动。因此,一个标签片段中,我有一个按钮,chartsButton。我有我的onclicklistener全部搞定它,这里的onClick的方法:

I want to launch a new fragment to view some data. Currently, I have a main activity that has a bunch of actionbar tabs, each of which is a fragment. So, within a tab fragment, I have a button, chartsButton. I have my onclicklistener all set for it, and here's the onClick method:

public OnClickListener chartsListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        Intent chartFragment = new Intent();
        startActivity(chartFragment);   
    }
};

现在,正如我所说,这个监听器是一个扩展片段一类中。所以,我想通过有意推出一个新片段(chartsFragment)更换整个屏幕。当用户点击回来,它会带他们回到标签和主要活动。这是我的图表片段:

Now, as I said, this listener is within a class that extends Fragment. So, I want to launch a new fragment (chartsFragment) via the intent to replace the whole screen. When the user clicks back, it'll bring them back to the tabs and main activity. Here's my chart fragment:

public class chartsFragment extends Fragment {

    public View onCreateView() {
        //LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState
        LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        return (inflater.inflate(R.layout.chartfragment, null));
    }
}

目前的错误我处理的:android.content.ActivityNotFoundException:无活动来处理意图{}。这很好,我知道我可以使用getActivity()。startActivity(chartsFragment),但会导致同样的错误。我想,我所期待的在这里,是我怎么启动一个意图从一个片段导致打开一个新片段中?

The current error I am dealing with: "android.content.ActivityNotFoundException: No Activity found to handle Intent { }". That's fine, I understand that I could use getActivity().startActivity(chartsFragment), but that results in the same error. I suppose what I am looking for here, is how do I launch an intent from within a fragment that results in opening a new fragment?

推荐答案

您无法打开新的片段。片段需要始终主办的活性。如果该片段是在相同的活动(如标签),然后返回键导航将是棘手我假设你想与该片段打开一个新窗口。

You cannot open new fragments. Fragments need to be always hosted by an activity. If the fragment is in the same activity (eg tabs) then the back key navigation is going to be tricky I am assuming that you want to open a new screen with that fragment.

所以,你会简单地创建一个新的活动,并把新的片段在那里。这项活动将随即反应过来的意图或者明确地通过活动课或隐式通过意图过滤器秒。

So you would simply create a new activity and put the new fragment in there. That activity would then react to the intent either explicitly via the activity class or implicitly via intent filters.