标签:
1、activity调用fragment,可直接通过activity内fragment的运用调用其公共方法;
2、fragment调用activity,利用getActivity(),如下:
((MainActivity) getActivity()).mainLog("hello"); //mainLog为activity中定义的方法
备注:此时要注意使用getActivity时要保证该activity与fragment关联;对动态生成的fragment,知道commit提交后,才进入fragment的oncreate.
3、回调,为满足activity与fragment的解耦,也可采用回调的方式,如下:
3.1 在fragment中定义一个回调接口,并对外暴露设置接口的方法
public class DemoFragment extends Fragment { private Button mButton; private FragmentListner listener; public interface FragmentListner { void onFragmentClick(); } public void setFragmentListner(FragmentListner listener){ this.listener = listener; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_main, container, false); mButton = (Button)view.findViewById(R.id.button1); mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(null != listener){ listener.onFragmentClick(); } } }); return view; } }
3.2 在activity中设置该方法(该例子中直接由fragment的按键触发fragment切换)
public class MainActivity extends FragmentActivity { private DemoFragment mDemo; private OtherFragment mDemo2; private Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mButton = (Button)findViewById(R.id.button3); mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FragmentManager fm = getSupportFragmentManager(); FragmentTransaction transaction = fm.beginTransaction(); mDemo = new DemoFragment(); mDemo.setFragmentListner(new FragmentListner(){ @Override public void onFragmentClick() { FragmentManager fm = getSupportFragmentManager(); FragmentTransaction transaction = fm.beginTransaction(); mDemo2 = new OtherFragment(); transaction.replace(R.id.fragment_content, mDemo2); transaction.addToBackStack(null); transaction.commit(); } }); transaction.replace(R.id.fragment_content, mDemo); transaction.addToBackStack(null); transaction.commit(); } }); } }
标签:
原文地址:http://www.cnblogs.com/Fredric-2013/p/4356787.html