在AndroidManifest.xml中声明活动使用一个Intent

问题描述 投票:0回答:1

我有以下Intent对象,我试图从片段SeventhFragment.java传递到另一个片段(SixthFragment.java)。

Intent i = new Intent(getContext(), SixthFragment.class);
i.putExtra("officeHour", hour);
startActivity(i); // this code is in SeventhFragment.java

在SixthFragment.java中,我有下面的代码来尝试取回这个对象。

Intent intent = (Intent) getActivity().getIntent(); // this code is in SixthFragment.java.
OfficeHour add = (OfficeHour) intent.getSerializableExtra("officeHour");

然而,我得到了一个异常。

android.content.ActivityNotFoundException: Unable to find explicit activity class 
{com.example.app/com.example.app.SixthFragment}; have you declared 
this activity in your AndroidManifest.xml?

我知道这意味着我需要在AndroidManifest.xml中添加一个活动声明 但我不知道我应该添加什么,应该如何格式化。顺便说一下,我已经尝试着四处寻找已有的问题,我还是不知道我的manifest中到底该写些什么。谢谢!我有以下的意图对象。

java android android-studio android-layout android-xml
1个回答
0
投票

A Fragment 始终需要由一个 Activity. 你不能在片段之间通过使用 Intent. 相反,你可以使用一个 FragmentTransaction 并将数据作为一个参数传递。

// this code is in SeventhFragment's underlying Activity
Fragment f = new SixthFragment();
Bundle args = new Bundle();
args.putSerializable("officeHour", hour);
f.setArguments(args);

// Execute a transaction to replace SeventhFragment with SixthFragment
FragmentTransaction ft = getFragmentManager().beginTransaction();
// R.id.myfragment needs to be defined in your Activity's layout resource
ft.replace(R.id.myfragment, f);
ft.commit();

然后你就可以在 "参数 "中检索到参数值 SixthFragment's onCreateView:

public class SixthFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        OfficeHour add = (OfficeHour) getArguments().getSerializable("officeHour");
        // ...
    }
}

或者,你可以嵌入 SixthFragment 自成 Activity 并使用意念启动它。

你可以在官方的 Fragment 文件.


0
投票

Intent是用来开始新的活动。你不能使用Intent.To改变片段。

试试下面的链接和代码来实现fragments。

fragmnets 1 片段详解

   FristFragment firstFragmentInstance=new FirstFragment();
    FragmentManager firstFragmentManager=getSupportFragmentManager();
    FragmentTransaction firstFragmentTransaction=firstFragmentManager.beginTransaction();
    firstFragmentTransaction.add(R.id.content_main,firstFragmentInstance,"").commit();

并更换碎片

   FristFragment firstFragmentInstance=new FirstFragment();
    FragmentManager firstFragmentManager=getSupportFragmentManager();
    FragmentTransaction firstFragmentTransaction=firstFragmentManager.beginTransaction();
    firstFragmentTransaction.replace(R.id.content_main,firstFragmentInstance,"first_fragment_tag").addToBackStack(null).commit()
© www.soinside.com 2019 - 2024. All rights reserved.