上一篇文章我们理解怎样使用接口回调的方式将数据从Fragment传递到Activity中,这里我们将探讨如何将数据从Activity传到Fragment中。
思路:把数据先保存到Bundle中,然后在调用setArguments()方法进行传递。
MainActivity.java代码:
public class MainActivity extends FragmentActivity { private FragmentManager manager; private FragmentTransaction transaction; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /* 获取manager */ manager = this.getSupportFragmentManager(); /* 创建事物 */ transaction = manager.beginTransaction(); /* 创建LeftFragment*/ LeftFragment leftFragment = new LeftFragment(); /*创建一个Bundle用来存储数据,传递到Fragment中*/ Bundle bundle = new Bundle(); /*往bundle中添加数据*/ bundle.putString("name", "廖泽民"); /*把数据设置到Fragment中*/ leftFragment.setArguments(bundle); /* 把Fragment添加到对应的位置 */ transaction.add(R.id.left, leftFragment, "left"); /* 提交事物 */ transaction.commit(); } }
public class LeftFragment extends Fragment { public LeftFragment() { // TODO Auto-generated constructor stub } @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { /*动态加载布局*/ View view = inflater.inflate(R.layout.left, null); /*从动态布局中获取控件*/ TextView txtView = (TextView) view.findViewById(R.id.txt); /*通过getArgments()方法获取从Activity传过来的值*/ Bundle bundle = this.getArguments(); /*为TextView设置值*/ txtView.setText(bundle.getString("name")); return view; } @Override public void onPause() { // TODO Auto-generated method stub super.onPause(); } }
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" tools:context=".MainActivity" > <LinearLayout android:id="@+id/left" android:layout_width="224dp" android:layout_height="match_parent" android:background="#CCCCCC" android:orientation="vertical" > </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:orientation="vertical" > </LinearLayout> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/txt" android:layout_width="fill_parent" android:layout_height="fill_parent"/> </LinearLayout>