1.activity向fragment傳值
/*
* 向fragment傳值
* */
FragmentTransaction ft = fm.beginTransaction();
testFragment = new TestFragment();
//利用bundle傳值
Bundle bundle=new Bundle();
bundle.putString("name","text");
testFragment.setArguments(bundle);
ft.add(R.id.lin, testFragment,"testFragment");
ft.show(testFragment);
ft.commit();
fragment接收
/* * 獲取activity傳的值 * */ Bundle bundle = getArguments(); String name = bundle.getString("name");
2.fragment向activity傳值
fragment中
定義一個接口 實現一個方法
private MyTextListener textListener; public interface MyTextListener{ public void getText(String text); }
/* * 源碼註釋:Called when a fragment is first attached to its activity. * 當片段首次附加到其活動時調用 也就是fragment首次被添加到activity時調用 只調用一次 * */ //onAttach方法中關聯一下對象 @Override public void onAttach(Context context) { textListener=(MyTextListener)context; super.onAttach(context); Log.i("iamchan", "onAttach"); }
onCreateView方法中調用getText方法
textListener.getText("iamchan");
activity中
實現MyTextListener接口
實現方法獲取數據