安卓Fragment和Activity之间的数据通讯
Fragment是Android3.0之后才推出来的。可以用来做底部菜单,现在很多APP都有用到这个底部菜单。当然TabHost也可以用来做底部菜单,但是Fragment来做,动画效果这些可以做得更炫。
Fragment和Activity之间是可以相互进行参数传送这些。但是Fragment不可以直接就将数据传送到另外一个Fragment,而是借助Activity,先传到Activity,然后再通过Activity传到Fragment。 所以实现Fragment和Activity之间的数据传送是很关键的。
(1)先创建一个Interface接口IBnCallListener,用来实现两者之间的数据传送。
package com.util; /** * 传送Fragment和FragmentActivity之间的控件交互信息 * */ public interface IBtnCallListener { public void transfermsg(); }
(2)创建Activity类实现IbtnCallListener接口,重载onAttachFragment(Fragment fragment)方法和transfermsg()方法,然后transfermsg()方法就根据自己项目需要去调用了
package com.activity; /** * *主界面类 *fragment是3.0以后的东西,为了在低版本中使用fragment就要用到android-support-v4.jar兼容包, *而fragmentActivity就是这个兼容包里面的,它提供了操作fragment的一些方法,其功能跟3.0及以后的版本的Activity的功能一样。 */ public class MainActivity extends FragmentActivity implements IBtnCallListener{ //RadioButton private RadioButton radioBtn; private Intent intent; private Bundle bundle; private IBtnCallListener mBtnCallListener; private Bundle sendBundle; private MyFragment mFragment; FragmentTransaction ft; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //设置无标题 requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); } ... @Override public void onAttachFragment(Fragment fragment) { try { mBtnCallListener=(IBtnCallListener) fragment; } catch (Exception e) { } super.onAttachFragment(fragment); } @Override public void transfermsg() { radioBtn.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.tab_found_pressed_icon, 0, 0); radioBtn.setTextColor(mFound.getResources().getColor(R.color.topbar_bg)); if(mFoundFragment == null){ //关键代码,肯定要这三句代码的,其它的根据自己的项目需要 mFragment = new MyFragment(); sendBundle = new Bundle(); sendBundle.putString("test", "Android"); //transfermsg(); mFragment.setArguments(sendBundle); ft.add(R.id.fg_content,mFragment); } ft.show(mFoundFragment); ft.commit(); } }
(3)Fragment类实现IBtnCallListener接口类
/** * MyFragMent类 */ public class MyFragment extends Fragment implements IBtnCallListener{ private Bundle bundle; IBtnCallListener mbtnListener; private String test; //@Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.found,container,false); transfermsg(); return view; } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onAttach(Activity activity) { try { mbtnListener=(IBtnCallListener) activity; } catch (Exception e) { // TODO: handle exception throw new ClassCastException(activity.toString() + "must implement mbtnListener"); } super.onAttach(activity); } @Override public void transfermsg() { bundle = getArguments(); test = bundle.getString("test"); System.out.println("由Activity传输过来的信息"); Toast.makeText(getActivity(), test, 1000).show(); } }
IT程序员