【发布时间】:2015-03-04 04:46:06
【问题描述】:
我有 2 个Fragments。
当我点击Fragment 1 中的按钮时,我会在这里做什么:
- 我设置了变量
String title = "Lady Gaga"。 - 我会显示
Fragment 2。
当Fragment 2 显示时,我想显示标题文本。
怎么做?
【问题讨论】:
-
使用单例模式传递数据字符串
我有 2 个Fragments。
当我点击Fragment 1 中的按钮时,我会在这里做什么:
String title = "Lady Gaga"。Fragment 2。当Fragment 2 显示时,我想显示标题文本。
怎么做?
【问题讨论】:
您可以使用捆绑包来传递数据:
Bundle data = new Bundle();
data.putString("title", "my title");
Fragment fragment2 = new Fragment2();
fragment2.setArguments(data);
FragmentTransaction agm_ft = getSupportFragmentManager()
.beginTransaction();
agm_ft.replace(R.id.frag_containor, fragment2,
"agm_frag");
agm_ft.addToBackStack(null);
agm_ft.commit();
并在下一个片段中取回它:
Bundle getData = getArguments();
title = getData.getString("title");
【讨论】:
1) 创建Interface
public interface TitleChangeListener {
public void onUpdateTitle(String title);
}
2) 在Fragment 2
创建一个public 方法
public void setTitle(String title){
//Do Somthing
}
3)让Activity实现Interface TitleChangeListener并覆盖onUpdateTitle
public void onUpdateTitle(String title){
fragment2.setTitle(title);
}
4) 在按钮中 onClickListner ,第一个 Fragment
TitleChangeListener listener=(TitleChangeListener)getActivity();
listener.onUpdateTitle("Lady Gaga");
【讨论】:
要从一个片段获取字符串到另一个片段,您必须使用捆绑包并将它们设置为如下参数:
//on button click
String title = "Lady Gaga";
Fragment fr = new Final_Categories_Fragment();
Bundle b = new Bundle();
b.putString("title", title);
fragmentManager.beginTransaction()
.add(R.id.list_frame, fr, "last").commit();
fr.setArguments(b);
//Now on another fragment you have to get this argument
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.sub_child_category_listview,
container, false);
...
String title = getArguments().getString("title");
...
return rootView;
}
【讨论】: