我有2 Fragments
。
当我点击Fragment 1
中的按钮时,我会这样做:
String title = "Lady Gaga"
。Fragment 2
。显示Fragment 2
时,我想显示标题文字。
怎么做?
答案 0 :(得分:1)
您可以使用捆绑包传递数据:
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 :(得分:0)
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");
答案 2 :(得分:0)
要从一个片段到另一个片段获取字符串,您必须使用bundle并将它们设置为如下参数:
//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;
}