在我的应用程序中,我需要将两个字符串从一个片段传递到另一个片段,最后传递到最后一个片段。基本上有一个带有FrameLayout的活动,其中各种片段被替换。
问题在于我认为我做了太多步骤,而且这种方式需要花费太多时间。 有更快的方法吗?我很困惑。
这是我的代码:
Frag1.java
//...Initiate frag2...
//Pass strings as arguments
Bundle args = new Bundle();
args.putString("String A", edittext1.getText().toString());
args.putString("String B", edittext2.getText().toString());
frag2.setArguments(args);
//Replace this fragment with the frag2 that has tabhost in it
manager.beginTransaction()
.replace(R.id.container, frag2).addToBackStack(null).commit();
Frag2.java
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Resources resources = getActivity().getResources();
mRoot = inflater.inflate(R.layout.frag2, container, false);
//Get tabhost and set it up
mTabHost = (TabHost) mRoot.findViewById(R.id.tabhost);
mTabHost.setup();
FragmentManager manager = getFragmentManager();
//Get the arguments again, and pass it to the fragment that will go inside tab1
Bundle args = new Bundle();
args.putString("String A", getArguments().getString("String A"));
args.putString("String B", getArguments().getString("String B"));
//...Initiate frag3...
frag3.setArguments(args);
//Add it to the tab
manager.beginTransaction().add(R.id.tab1, frag3).commit();
//Set content of tabs
TabSpec spec1 = mTabHost.newTabSpec("tab1");
spec1.setIndicator("tab1");
spec1.setContent(R.id.tab1);
TabSpec spec2 = mTabHost.newTabSpec("tab2");
spec2.setIndicator("tab2");
spec2.setContent(R.id.tab2);
mTabHost.addTab(spec1);
mTabHost.addTab(spec2);
return mRoot;
}
使用tabhost进行Frag2布局,可能很有用
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#EFEFEF" >
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<FrameLayout
android:id="@+id/tab1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="60dp" >
</FrameLayout>
<FrameLayout
android:id="@+id/tab2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="60dp" >
</FrameLayout>
</FrameLayout>
</TabHost>
Frag3.java
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frag3, container, false);
//Recover again the strings..
stringA = getArguments().getString("String A");
stringB = getArguments().getString("String B");
//Recover TextViews in tab1
TextView tv1 = (TextView) rootView.findViewById(R.id.tv1);
TextView tv2 = (TextView) rootView.findViewById(R.id.tv2);
//...Do something with strings...
//Set text of them with strings
tv1.setText(String.valueOf(stringA));
tv2.setText(String.valueOf(stringB));
return rootView;
}