1、getActivity()調用父佈局context獲取實例
其實比較簡單,就是在activityB中寫一個方法用public修飾可見,將數據賦值返回這個參數,在fragment中getActivity()獲取到activity的實例強制轉換爲actvityB,然後調用方法,得到參數。這是我覺得理所當然的方法。。。
1、activityB中的代碼片
public int test(){
//將參數賦值返回
return param;
}
2、fragment中的代碼片
(activityB)getActivity() act=new activityB();
int param=act.test();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
2、使用bundle,fragment有個setArguments(bundle)的方法,可以傳遞數據。推薦使用的方法,這個纔是activity向fragment傳遞數據的正確打開方式。
1、activity傳遞給fragment數據的方法,通過setArauments就可以了,傳遞的是bundle數據包。
- 1
- 1
String[] strTitle = {"實時信息","提醒通知","活動路線","相關設置"};
listView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,strTitle));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MyFragment myFragment = new MyFragment();
Bundle bundle=new Bundle();
bundle.putString("text","你點擊的座標是"+position+"");
myFragment.setArguments(bundle);
FragmentManager fm=getSupportFragmentManager();
fm.beginTransaction().replace(R.id.content_frame,myFragment).commit();
drawerLayout.closeDrawer(listView);
}
});
}
2、fragment中只要getArguments()就可以得到這個bundle了。
- 1
- 1
public class MyFragment extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView=inflater.inflate(R.layout.fragment_planet,container,false); TextView textView= (TextView) rootView.findViewById(R.id.tv_content); String text = getArguments().getString("text"); textView.setText(text); return rootView; } }