接口作用之一-------------------发命令给其他类
子界面经常要传命令给主Activity,让主Activity来实行调用其他界面的功能,怎么完成,就看接口的使用:
(1)首先在子界面定义接口,这里子界面是一个Fragment:
public interface MeClickInterface {
void meClick();
}
(2)然后再Fragment实现接口的引用:
private MeClickInterface mci;
(3)定义方法,将导入的引用全局化(这一步很重要,如果没有这一步,实现接口的类和定义接口的类将不会相关联):
public void setMeclick(final MeClickInterface mci){
this.mci=mci;
}
(4)在需要其他类实现功能的位置用引用调用接口里的方法
如:
public void onClick(View v) {
if (null != mci) {
mci.meClick();
}
}
(5)在需要实现功能的类实现此接口
public class MainActivity extends FragmentActicity implements MeClickInterface
(6)在实现接口的方法中执行相应的操作
public void meClick() {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
MeFragment fragment = new MeFragment(this);
ft.replace(R.id.hallLinear, fragment);
ft.addToBackStack(null);
ft.commit();
}
(7)如果想Activity初始的时候就显示某Fragment就在onCreate()中:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
HallFragment fragment = new HallFragment(this);
********下面一句是将本Activity作为引用导入产生接口类的的方法,勿忘**************
fragment.setMci(this);
ft.add(R.id.hallLinear, fragment);
ft.commit();