通过片段内的意图启动片段 [英] Start a fragment via Intent within a Fragment

查看:24
本文介绍了通过片段内的意图启动片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想启动一个新的片段来查看一些数据.目前,我有一个主要活动,它有一堆操作栏选项卡,每个选项卡都是一个片段.因此,在选项卡片段中,我有一个按钮 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);   
    }
};

现在,正如我所说,这个监听器在一个扩展 Fragment 的类中.所以,我想通过替换整个屏幕的意图启动一个新的片段 (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:没有找到处理 Intent {} 的活动".没关系,我知道我可以使用 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.

因此,您只需创建一个新活动并将新片段放入其中.然后,该活动将通过活动类显式地或通过intent filters 隐式地对意图做出反应.

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.

这篇关于通过片段内的意图启动片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆