Android 如何将按钮单击时的值(片段1)传递给onCreateView(片段2)?
我有2个Android 如何将按钮单击时的值(片段1)传递给onCreateView(片段2)?,android,fragment,Android,Fragment,我有2个片段。 当我点击片段1中的按钮时,我要做的是: 我设置变量String title=“Lady Gaga” 我将显示片段2 当显示片段2时,我想显示标题文本 如何操作?您可以使用捆绑包传递数据: Bundle data = new Bundle(); data.putString("title", "my title"); Fragment fragment2 = new Fragment2();
片段
。
当我点击片段1
中的按钮时,我要做的是:
String title=“Lady Gaga”
片段2
片段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) 创建一个界面
public interface TitleChangeListener {
public void onUpdateTitle(String title);
}
2) 在片段2中
创建一个public
方法
public void setTitle(String title){
//Do Somthing
}
3) 让Activity
实现接口标题ChangeListener
并覆盖onUpdate标题
public void onUpdateTitle(String title){
fragment2.setTitle(title);
}
4) 在按钮onClickListner
中,第一个片段
TitleChangeListener listener=(TitleChangeListener)getActivity();
listener.onUpdateTitle("Lady Gaga");
要从一个片段到另一个片段获取字符串,必须使用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;
}
使用单例模式传递数据字符串检查文档后。我在getSupportFragmentManager()中遇到问题。错误为“找不到符号getSupportFragmentManager”。我正在使用fragment,主要是Activity.im在getSupportFragmentManager()中遇到问题。错误为“找不到符号getSupportFragmentManager”。我正在使用fragment,我的主要任务是活动。使用FragmentTransaction agm_ft=getActivity().getSupportFragmentManager().beginTransaction();