(轉)Activity和Fragment傳遞資料的兩種方式
阿新 • • 發佈:2018-11-27
1、第一種方式,也是最常用的方式,就是使用Bundle來傳遞引數
MyFragment myFragment = new MyFragment();
Bundle bundle = new Bundle();
bundle.putString("DATA",values);//這裡的values就是我們要傳的值
myFragment.setArguments(bundle);
然後在Fragment中的onCreatView方法中,通過getArgments()方法,獲取到bundle物件,然後通過getString的key值拿到我們傳遞過來的值。
2、第二種方式,是在宿主Activity中定義方法,將要傳遞的值傳遞到Fragment中,在Fragment中的onAttach方法中,獲取到這個值。
//宿主activity中的getTitles()方法
public String getTitles(){
return "hello";
}
//Fragment中的onAttach方法
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
titles = ((MainActivity) activity).getTitles();
}
//通過強轉成宿主activity,就可以獲取到傳遞過來的資料
3、下面在擴充套件一下建立Fragment和傳遞數值
如果我們不需要傳遞數值,那就直接可以在宿主activity中,跟平常一樣建立fragment,但是如果我們需要傳遞資料的話,可以使用newInstance(資料)方法來傳遞,這個方法是自己定義的,但是是定義在Fragment中的一個靜態方法。
static MyFragment newInstance(String s){ MyFragment myFragment = new MyFragment(); Bundle bundle = new Bundle(); bundle.putString("DATA",s); myFragment.setArguments(bundle); return myFragment; } //同樣,在onCreatView中直接獲取這個值 @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.layout_fragment,container,false); Bundle bundle = getArguments(); String data = bundle.getString("DATA"); tv = (TextView) view.findViewById(R.id.id_fm_tv); if(data != null){ tv.setText(data); } return view; }
在宿主activity中,建立Fragment
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,android.R.anim.fade_out);
fragment1 = MyFragment.newInstance("這是第一個fragment");//這裡只需要直接呼叫這個方法,就建立了一個fragment
fragment2 = MyFragment.newInstance("這是第二個fragment");
fragment3 = MyFragment.newInstance("這是第三個fragment");