android - 通过 Fragment 中的 Intent 启动 Fragment

标签 android android-intent android-fragments

我想启动一个新 fragment 来查看一些数据。目前,我有一个主要 Activity ,其中包含一堆操作栏选项卡,每个选项卡都是一个 fragment 。所以,在一个标签 fragment 中,我有一个按钮,chartsButton。我已经为它设置了我的 onclicklistener,这是 onClick 方法:

public OnClickListener chartsListener = new OnClickListener() {

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

现在,正如我所说,此监听器位于扩展 Fragment 的类中。所以,我想通过替换整个屏幕的 Intent 来启动一个新的 fragment (chartsFragment)。当用户点击返回时,它会将他们带回选项卡和主要 Activity 。这是我的图表 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 {} 的 Activity ”。没关系,我知道我可以使用 getActivity().startActivity(chartsFragment),但这会导致同样的错误。我想我在这里寻找的是如何从 fragment 中启动一个 Intent 以打开一个新 fragment ?

最佳答案

问题的答案很简单:用新的 Fragment 替换当前的 Fragment 并将事务推送到后台堆栈。这保留了后退按钮的行为...

创建一个新的 Activity 确实违背了使用 fragment 的整个目的......非常适得其反。

@Override
public void onClick(View v) {
    // Create new fragment and transaction
    Fragment newFragment = new chartsFragment(); 
    // consider using Java coding conventions (upper first char class names!!!)
    FragmentTransaction transaction = getFragmentManager().beginTransaction();

    // Replace whatever is in the fragment_container view with this fragment,
    // and add the transaction to the back stack
    transaction.replace(R.id.fragment_container, newFragment);
    transaction.addToBackStack(null);

    // Commit the transaction
    transaction.commit(); 
}

http://developer.android.com/guide/components/fragments.html#Transactions

关于android - 通过 Fragment 中的 Intent 启动 Fragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9831728/

相关文章:

android - fragment 动画 : Fatal signal 11 (SIGSEGV) Crash

android - 遵循Mapbox初学者教程会返回 “Manifest merger failed”错误

java - 数据对齐与缓存局部性

android - 哎呀!有一个 ...previewing this pdf document android

android - 需要额外的传递给 Activity

java - fragment 到 fragment 的通信——为什么接口(interface)真的是必要的?

android - 如何在 Fire Phone 上启用开发者选项和 ADB?

android - 使用TextView的onClick跳转到下一页

android - 使用标志 FLAG_UPDATE_CURRENT 时,小部件 onclick 未决 Intent 不会触发

java - Android:滚动包含recyclerView的 subview 时如何滚动parentView