1、第一種方式,也是最常用的方式,就是使用Bundle來傳遞參數
OneFragment fragment = new OneFragment (); Bundle bundle = new Bundle(); bundle.putString("sky",values);//這里的values就是我們要傳的值 fragment.setArguments(bundle);然后在Fragment中的onCreatView方法中,通過getArgments()方法,獲取到bundle對象,然后通過getString的key值拿到我們傳遞過來的值。
2、第二種方式,是在宿主Activity中定義方法,將要傳遞的值傳遞到Fragment中,在Fragment中的onAttach方法中,獲取到這個值。
//宿主activity中的getContent()方法public String getContent(){ return "who are you";}//Fragment中的onAttach方法 @Override public void onAttach(Activity activity) { super.onAttach(activity); content= ((MainActivity) activity).getContent(); } //通過強轉成宿主activity,就可以獲取到傳遞過來的數據3、下面再說一下創建Fragment和傳遞數值
如果我們不需要傳遞數值,那就直接可以在宿主activity中,跟平常一樣創建fragment,但是如果我們需要傳遞數據的話,可以使用newInstance(數據)方法來傳遞,這個方法是自己定義的,但是是定義在Fragment中的一個靜態方法。
static OneFragment newInstance(String s){ OneFragment fragment = new OneFragment (); Bundle bundle = new Bundle(); bundle.putString("DATA",s); fragment.setArguments(bundle); return fragment ; }//同樣,在onCreatView中直接獲取這個值 @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.layout_fragment,container,false); Bundle bundle = getArguments(); String content= bundle.getString("sky"); tv = (TextView) view.findViewById(R.id.tv_content); if(data != null){ tv.setText(content); } return view; }新聞熱點
疑難解答