回调接口
/** * 回调接口 * @author Chillax K. */ public interface ReCallBack { public void doSomething(); }
/** * 回调接口 * @author Chillax K. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class MyFragment extends Fragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.message_layout, container, false); view.findViewById(R.id.button1).setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub Toast.makeText(getActivity(), "点击回调按钮,调用回调函数", 0).show(); if(myReCallBack != null){ myReCallBack.doSomething(); } } }); return view; } private ReCallBack myReCallBack; public void setMyReCallBack(ReCallBack myReCallBack) { this.myReCallBack = myReCallBack; } }
/** * 回调接口 * @author Chillax K. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class MainActivity extends Activity { /** * 用于展示消息的Fragment */ private MyFragment messageFragment; /** * 用于对Fragment进行管理 */ private FragmentManager fragmentManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //设置无标题 requestWindowFeature(Window.FEATURE_NO_TITLE); //设置全屏 // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, // WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_main); fragmentManager = getFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); messageFragment = new MyFragment(); //设置回调变量 messageFragment.setMyReCallBack(mReCallBack); transaction.add(R.id.content, messageFragment); transaction.commit(); } ReCallBack mReCallBack = new ReCallBack() { @Override public void doSomething() { // TODO Auto-generated method stub Toast.makeText(getBaseContext(), "回调了MainActivity", 0).show(); } };
原文地址:http://blog.csdn.net/chillax_li/article/details/44173465