如何将包添加到 Android 片段

How to add bundle to Android fragment

如何将我创建的包添加到:

int index = 0;

这是我尝试添加捆绑包的代码。我哪里错了?

public class NewsItemFragment extends Fragment {
public static final String KEY_NEWS_ITEM_INDEX = "news_item_index";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // TODO:  Hmmm, how do we get this index?
    int index = 0;
    getActivity().setTitle(News.headlines[index]);
    View view = inflater.inflate(R.layout.fragment_newsitem, container, false);
    return view;
}

    public static NewsItemFragment createInstance(int index) {
    NewsItemFragment fragment = new NewsItemFragment();
    Bundle bundle = new Bundle();
    bundle.putInt("news_item_index", index);
    fragment.setArguments(bundle);
    index = bundle.getArguments().getInt( NewsItemFragment.KEY_NEWS_ITEM_INDEX);
    return fragment;
}


@Override
public void onStop() {
    super.onStop();
    getActivity().setTitle(getResources().getString(R.string.app_name));
}

}

这里是这个问题的link:

https://teamtreehouse.com/community/great-job-thanks-now-in-newsitemfragmentjava-update-the-line-that-says-int-index-0-to-access-the-new-bundle

只需将 int index = 0; 替换为

int index = getArguments().getInt( NewsItemFragment.KEY_NEWS_ITEM_INDEX);

这里有一个例子:

  • 发送信息的片段

frag_more_informations frag_more_informations = new frag_more_informations(); Bundle bundle = new Bundle(); bundle.putCharSequence(bundle_string, txt_results_experience.getText()); frag_more_informations.setArguments(bundle); FragmentManager manager = getActivity().getSupportFragmentManager(); manager.beginTransaction().replace(R.id.framelayout_secundary, frag_more_informations, frag_more_informations.getTag()).commit();

  • 收到它的片段

Bundle bundle = this.getArguments(); if (bundle != null) { CharSequence myInt = bundle.getCharSequence(bundle_string); txt_results_experience.setText(String.valueOf(myInt)); }