動態(tài)加載的Fragment
Activity => Fragment
實例化 bundle類 傳遞給 Fragment
//動態(tài)加載?fragment ????????Fragment?fragment?=?new?Fragment();?//這個是我們自己定義的?Fragment ????????FragmentManager?fragmentManager?=?getFragmentManager(); ????????FragmentTransaction?fragmentTransaction?=?fragmentManager.beginTransaction(); ????????//實例化bundle類 ????????Bundle?bundle?=?new?Bundle(); ????????bundle.putString("title","學(xué)習(xí)雷鋒好榜樣"); ????????//傳遞數(shù)據(jù) ????????fragment.setArguments(bundle); ????????fragmentTransaction.addToBackStack(null);?//后退按鍵?允許 ????????fragmentTransaction.add(R.id.linear,fragment); ????????fragmentTransaction.commit();
Fragment =>Activity
實質(zhì)就是調(diào)用Activity中的方法
Fragment.java
public?interface?MyListener{ ????????public?void?sayHello(String?str); ????} ????@Override ????public?void?onAttach(Activity?activity)?{ ????????MyListener?listener?=?(MyListener)getActivity(); ????????listener.sayHello("Fragment?傳遞給?Activity?的數(shù)據(jù)!"); ????????super.onAttach(activity); ????}
MainActivity.java
public?class?MainActivity?extends?ActionBarActivity?implements?Fragment.MyListener ... ... ???@Override ????public?void?sayHello(String?str)?{ ????????Toast.makeText(MainActivity.this,str,Toast.LENGTH_LONG).show(); ????}
靜態(tài)加載的Fragment
Activity => Fragment
實質(zhì)就是調(diào)用Fragment類中的方法
public?class?Fragment?extends?android.app.Fragment?{ ????private?String?str; ????public?void?setStr(String?str)?{ ????????this.str?=?str; ????} ????public?String?getStr()?{ ????????return?str; ????}
MainActivity.java
FragmentManager?fragmentManager?=?getFragmentManager(); ????????android.app.Fragment?fragmentById?=?fragmentManager.findFragmentById(R.id.fragment); ????????Fragment?fragment?=?(Fragment)fragmentById; ????????fragment.setStr("123");
注意:Fragment 的 onCreateView的時候,Activity中的 setStr沒有執(zhí)行
?所以是無法在接收到的
“
Fragment =>Activity (和動態(tài)加載一致)