1、getActivity()调用父布局context获取实例
其实比较简单,就是在activityB中写一个方法用public修饰可见,将数据赋值返回这个参数,在fragment中getActivity()获取到activity的实例强制转换为actvityB,然后调用方法,得到参数。这是我觉得理所当然的方法。。。
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
2、使用bundle,fragment有个setArguments(bundle)的方法,可以传递数据。推荐使用的方法,这个才是activity向fragment传递数据的正确打开方式。
- 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);
}
});
}
- 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; } }