Fragment與Activity通訊

程式碼修行者發表於2015-07-22

動態載入的Fragment

Activity => Fragment

例項化 bundle類 傳遞給 Fragment

//動態載入 fragment
        Fragment fragment = new Fragment(); //這個是我們自己定義的 Fragment
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        //例項化bundle類
        Bundle bundle = new Bundle();
        bundle.putString("title","學習雷鋒好榜樣");
        //傳遞資料
        fragment.setArguments(bundle);

        fragmentTransaction.addToBackStack(null); //後退按鍵 允許
        fragmentTransaction.add(R.id.linear,fragment);
        fragmentTransaction.commit();

Fragment =>Activity

實質就是呼叫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 的資料!");
        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();
    }

靜態載入的Fragment

Activity => Fragment

實質就是呼叫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沒有執行
所以是無法在接收到的

Fragment =>Activity (和動態載入一致)

相關文章