FragmentActivity与Fragment两者交互方法简介(转)

FragmentActivity与Fragment两者交互方法简介

分类: Fragment 2014-07-07 18:17 88人阅读 评论(0) 收藏 举报
在Android4.0后很多时候我们会大量使用到Fragment,Fragment与Activity的交互应该来说是非常重要的,但目前很多实例方法都只介绍了Fragment与Activity交互的方法,没有Activity与Fragment交互的方法,下面我来把解决的思路记录如下。
  1.首先我需要定义一个公共接口,用于将Fragment与FragmentActivity中的控件进行交互  
  1. public interface IBtnCallListener {
  2.   public void transfermsg();
  3.   }
public interface IBtnCallListener {

  public void transfermsg();
  }

2.当fragment中的Button控件需要与FragmentActivity中的Button控件交互时,在Fragment对应的子类中定义

  1. public class LaunchUIFragment extends Fragment implements
  2. IBtnCallListener{
  3.   IBtnCallListener mbtnListener;
  4.   private Button btn_Click;
  5.   @Override
  6.   public View onCreateView(LayoutInflater inflater, ViewGroup container,
  7.   Bundle savedInstanceState) {
  8.   View rootView = inflater.inflate(R.layout.fragment_selection_launch,
  9. container, false);
  10.   btn_Click=(Button) rootView.findViewById(R.id.bt_click);
  11.   btn_Click.setOnClickListener(new OnClickListener() {
  12.   @Override
  13.   public void onClick(View v) {
  14.   // TODO Auto-generated method stub
  15.   mbtnListener.transfermsg();
  16.   }
  17.   });
  18.   return rootView;
  19.   }
  20.   @Override
  21.   public void onActivityCreated(Bundle savedInstanceState) {
  22.   // TODO Auto-generated method stub
  23.   super.onActivityCreated(savedInstanceState);
  24.   }
  25.   @Override
  26.   public void onAttach(Activity activity) {
  27.   // TODO Auto-generated method stub
  28.   try {
  29.   mbtnListener=(IBtnCallListener) activity;
  30.   } catch (Exception e) {
  31.   // TODO: handle exception
  32.   throw new ClassCastException(activity.toString() + "must implement
  33. mbtnListener");
  34.   }
  35.   super.onAttach(activity);
  36.   }
  37.   @Override
  38.   public void transfermsg() {
  39.   // TODO Auto-generated method stub
  40.   System.out.println("由Activity传输过来的信息");
  41.   }
  42.   }
public class LaunchUIFragment extends Fragment implements
IBtnCallListener{   IBtnCallListener mbtnListener;
  private Button btn_Click;
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
  Bundle savedInstanceState) {
  View rootView = inflater.inflate(R.layout.fragment_selection_launch,
container, false);
  btn_Click=(Button) rootView.findViewById(R.id.bt_click);
  btn_Click.setOnClickListener(new OnClickListener() {
  @Override
  public void onClick(View v) {
  // TODO Auto-generated method stub
  mbtnListener.transfermsg();
  }
  });
  return rootView;
  }
  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onActivityCreated(savedInstanceState);
  }
  @Override
  public void onAttach(Activity activity) {
  // TODO Auto-generated method stub
  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() {
  // TODO Auto-generated method stub
  System.out.println("由Activity传输过来的信息");
  }
  }

同时在FragmentActivity中对应相应

  

  1. public class MainActivity extends FragmentActivity implements
  2. IBtnCallListener{
  3.   public static final String ARGUMENTS_NAME = "arg";
  4.   private RelativeLayout rl_nav;
  5.   private SyncHorizontalScrollView mHsv;
  6.   private RadioGroup rg_nav_content;
  7.   private ImageView iv_nav_indicator;
  8.   private ImageView iv_nav_left;
  9.   private ImageView iv_nav_right;
  10.   private ViewPager mViewPager;
  11.   private int indicatorWidth;
  12.   public static String[] tabTitle = { "选项1", "选项2", "选项3", "选项4", "选项5" };
  13. //标题
  14.   private LayoutInflater mInflater;
  15.   private TabFragmentPagerAdapter mAdapter;
  16.   private int currentIndicatorLeft = 0;
  17.   private Button Btn_Test;
  18.   @Override
  19.   protected void onCreate(Bundle savedInstanceState) {
  20.   super.onCreate(savedInstanceState);
  21.   setContentView(R.layout.activity_main);
  22.   findViewById();
  23.   initView();
  24.   setListener();
  25.   }
  26.   /*
  27.   private void setListener() {
  28.   mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
  29.   @Override
  30.   public void onPageSelected(int position) {
  31.   if(rg_nav_content!=null &&
  32. rg_nav_content.getChildCount()>position){
  33.   ((RadioButton)rg_nav_content.getChildAt(position)).performClick();
  34.   }
  35.   }
  36.   @Override
  37.   public void onPageScrolled(int arg0, float arg1, int arg2) {
  38.   }
  39.   @Override
  40.   public void onPageScrollStateChanged(int arg0) {
  41.   }
  42.   });
  43.   rg_nav_content.setOnCheckedChangeListener(new OnCheckedChangeListener()
  44. {
  45.   @Override
  46.   public void onCheckedChanged(RadioGroup group, int checkedId) {
  47.   if(rg_nav_content.getChildAt(checkedId)!=null){
  48.   TranslateAnimation animation = new TranslateAnimation(
  49.   currentIndicatorLeft ,
  50.   ((RadioButton) rg_nav_content.getChildAt(checkedId)).getLeft(), 0f,
  51. 0f);
  52.   animation.setInterpolator(new LinearInterpolator());
  53.   animation.setDuration(100);
  54.   animation.setFillAfter(true);
  55.   //执行位移动画
  56.   iv_nav_indicator.startAnimation(animation);
  57.   mViewPager.setCurrentItem(checkedId); //ViewPager 跟随一起 切换
  58.   //记录当前 下标的距最左侧的 距离
  59.   currentIndicatorLeft = ((RadioButton)
  60. rg_nav_content.getChildAt(checkedId)).getLeft();
  61.   mHsv.smoothScrollTo(
  62.   (checkedId > 1 ? ((RadioButton)
  63. rg_nav_content.getChildAt(checkedId)).getLeft() : 0) - ((RadioButton)
  64. rg_nav_content.getChildAt(2)).getLeft(), 0);
  65.   }
  66.   }
  67.   });
  68.   }
  69.   private void initView() {
  70.   DisplayMetrics dm = new DisplayMetrics();
  71.   getWindowManager().getDefaultDisplay().getMetrics(dm);
  72.   indicatorWidth = dm.widthPixels / 4;
  73.   LayoutParams cursor_Params = iv_nav_indicator.getLayoutParams();
  74.   cursor_Params.width = indicatorWidth;// 初始化滑动下标的宽
  75.   iv_nav_indicator.setLayoutParams(cursor_Params);
  76.   mHsv.setSomeParam(rl_nav, iv_nav_left, iv_nav_right, this);
  77.   //获取布局填充器
  78.   mInflater =
  79. (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
  80.   //另一种方式获取
  81.   // LayoutInflater mInflater = LayoutInflater.from(this);
  82.   initNavigationHSV();
  83.   mAdapter = new TabFragmentPagerAdapter(getSupportFragmentManager());
  84.   mViewPager.setAdapter(mAdapter);
  85.   Btn_Test=(Button) findViewById(R.id.btn_test);
  86.   Btn_Test.setOnClickListener(new OnClickListener() {
  87.   @Override
  88.   public void onClick(View v) {
  89.   // TODO Auto-generated method stub
  90.   mBtnCallListener.transfermsg();
  91.   }
  92.   });
  93.   }
  94.   */
  95.   private IBtnCallListener mBtnCallListener;
  96.   @Override
  97.   public void onAttachFragment(Fragment fragment) {
  98.   // TODO Auto-generated method stub
  99.   try {
  100.   mBtnCallListener=(IBtnCallListener) fragment;
  101.   } catch (Exception e) {
  102.   // TODO: handle exception
  103.   }
  104.   super.onAttachFragment(fragment);
  105.   }
  106.   @Override
  107.   public void transfermsg() {
  108.   // TODO Auto-generated method stub
  109.   System.out.println("由Fragment传输过来的信息");
  110.   }
  111.   /*
  112.   private void initNavigationHSV() {
  113.   rg_nav_content.removeAllViews();
  114.   for(int i=0;i
  115.   RadioButton rb = (RadioButton)
  116. mInflater.inflate(R.layout.nav_radiogroup_item, null);
  117.   rb.setId(i);
  118.   rb.setText(tabTitle[i]);
  119.   rb.setLayoutParams(new LayoutParams(indicatorWidth,
  120.   LayoutParams.MATCH_PARENT));
  121.   rg_nav_content.addView(rb);
  122.   }
  123.   }
  124.   private void findViewById() {
  125.   rl_nav = (RelativeLayout) findViewById(R.id.rl_nav);
  126.   mHsv = (SyncHorizontalScrollView) findViewById(R.id.mHsv);
  127.   rg_nav_content = (RadioGroup) findViewById(R.id.rg_nav_content);
  128.   iv_nav_indicator = (ImageView) findViewById(R.id.iv_nav_indicator);
  129.   iv_nav_left = (ImageView) findViewById(R.id.iv_nav_left);
  130.   iv_nav_right = (ImageView) findViewById(R.id.iv_nav_right);
  131.   mViewPager = (ViewPager) findViewById(R.id.mViewPager);
  132.   }
  133.   @Override
  134.   public boolean onCreateOptionsMenu(Menu menu) {
  135.   getMenuInflater().inflate(R.menu.main, menu);
  136.   return true;
  137.   }
  138.   public static class TabFragmentPagerAdapter extends
  139. FragmentPagerAdapter{
  140.   public TabFragmentPagerAdapter(FragmentManager fm) {
  141.   super(fm);
  142.   }
  143.   @Override
  144.   public Fragment getItem(int arg0) {
  145.   Fragment ft = null;
  146.   switch (arg0) {
  147.   case 0:
  148.   ft = new LaunchUIFragment();
  149.   break;
  150.   default:
  151.   ft = new CommonUIFragment();
  152.   Bundle args = new Bundle();
  153.   args.putString(ARGUMENTS_NAME, tabTitle[arg0]);
  154.   ft.setArguments(args);
  155.   break;
  156.   }
  157.   return ft;
  158.   }
  159.   @Override
  160.   public int getCount() {
  161.   return tabTitle.length;
  162.   }
  163.   }*/
  164.   }
public class MainActivity extends FragmentActivity implements
IBtnCallListener{   public static final String ARGUMENTS_NAME = "arg";
  private RelativeLayout rl_nav;
  private SyncHorizontalScrollView mHsv;
  private RadioGroup rg_nav_content;
  private ImageView iv_nav_indicator;
  private ImageView iv_nav_left;
  private ImageView iv_nav_right;
  private ViewPager mViewPager;
  private int indicatorWidth;
  public static String[] tabTitle = { "选项1", "选项2", "选项3", "选项4", "选项5" };
//标题
  private LayoutInflater mInflater;
  private TabFragmentPagerAdapter mAdapter;
  private int currentIndicatorLeft = 0;
  private Button Btn_Test;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  findViewById();
  initView();
  setListener();
  }
  /*
  private void setListener() {
  mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
  @Override
  public void onPageSelected(int position) {
  if(rg_nav_content!=null &&
rg_nav_content.getChildCount()>position){
  ((RadioButton)rg_nav_content.getChildAt(position)).performClick();
  }
  }
  @Override
  public void onPageScrolled(int arg0, float arg1, int arg2) {
  }
  @Override
  public void onPageScrollStateChanged(int arg0) {
  }
  });
  rg_nav_content.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
  @Override
  public void onCheckedChanged(RadioGroup group, int checkedId) {
  if(rg_nav_content.getChildAt(checkedId)!=null){
  TranslateAnimation animation = new TranslateAnimation(
  currentIndicatorLeft ,
  ((RadioButton) rg_nav_content.getChildAt(checkedId)).getLeft(), 0f,
0f);
  animation.setInterpolator(new LinearInterpolator());
  animation.setDuration(100);
  animation.setFillAfter(true);
  //执行位移动画
  iv_nav_indicator.startAnimation(animation);
  mViewPager.setCurrentItem(checkedId); //ViewPager 跟随一起 切换
  //记录当前 下标的距最左侧的 距离
  currentIndicatorLeft = ((RadioButton)
rg_nav_content.getChildAt(checkedId)).getLeft();
  mHsv.smoothScrollTo(
  (checkedId > 1 ? ((RadioButton)
rg_nav_content.getChildAt(checkedId)).getLeft() : 0) - ((RadioButton)
rg_nav_content.getChildAt(2)).getLeft(), 0);
  }
  }
  });
  }
  private void initView() {
  DisplayMetrics dm = new DisplayMetrics();
  getWindowManager().getDefaultDisplay().getMetrics(dm);
  indicatorWidth = dm.widthPixels / 4;
  LayoutParams cursor_Params = iv_nav_indicator.getLayoutParams();
  cursor_Params.width = indicatorWidth;// 初始化滑动下标的宽
  iv_nav_indicator.setLayoutParams(cursor_Params);
  mHsv.setSomeParam(rl_nav, iv_nav_left, iv_nav_right, this);
  //获取布局填充器
  mInflater =
(LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
  //另一种方式获取
  // LayoutInflater mInflater = LayoutInflater.from(this);
  initNavigationHSV();
  mAdapter = new TabFragmentPagerAdapter(getSupportFragmentManager());
  mViewPager.setAdapter(mAdapter);
  Btn_Test=(Button) findViewById(R.id.btn_test);
  Btn_Test.setOnClickListener(new OnClickListener() {
  @Override
  public void onClick(View v) {
  // TODO Auto-generated method stub
  mBtnCallListener.transfermsg();
  }
  });
  }
  */
  private IBtnCallListener mBtnCallListener;
  @Override
  public void onAttachFragment(Fragment fragment) {
  // TODO Auto-generated method stub
  try {
  mBtnCallListener=(IBtnCallListener) fragment;
  } catch (Exception e) {
  // TODO: handle exception
  }
  super.onAttachFragment(fragment);
  }
  @Override
  public void transfermsg() {
  // TODO Auto-generated method stub
  System.out.println("由Fragment传输过来的信息");
  }
  /*
  private void initNavigationHSV() {
  rg_nav_content.removeAllViews();
  for(int i=0;i
  RadioButton rb = (RadioButton)
mInflater.inflate(R.layout.nav_radiogroup_item, null);
  rb.setId(i);
  rb.setText(tabTitle[i]);
  rb.setLayoutParams(new LayoutParams(indicatorWidth,
  LayoutParams.MATCH_PARENT));
  rg_nav_content.addView(rb);
  }
  }
  private void findViewById() {
  rl_nav = (RelativeLayout) findViewById(R.id.rl_nav);
  mHsv = (SyncHorizontalScrollView) findViewById(R.id.mHsv);
  rg_nav_content = (RadioGroup) findViewById(R.id.rg_nav_content);
  iv_nav_indicator = (ImageView) findViewById(R.id.iv_nav_indicator);
  iv_nav_left = (ImageView) findViewById(R.id.iv_nav_left);
  iv_nav_right = (ImageView) findViewById(R.id.iv_nav_right);
  mViewPager = (ViewPager) findViewById(R.id.mViewPager);
  }
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
  }
  public static class TabFragmentPagerAdapter extends
FragmentPagerAdapter{
  public TabFragmentPagerAdapter(FragmentManager fm) {
  super(fm);
  }
  @Override
  public Fragment getItem(int arg0) {
  Fragment ft = null;
  switch (arg0) {
  case 0:
  ft = new LaunchUIFragment();
  break;
  default:
  ft = new CommonUIFragment();
  Bundle args = new Bundle();
  args.putString(ARGUMENTS_NAME, tabTitle[arg0]);
  ft.setArguments(args);
  break;
  }
  return ft;
  }
  @Override
  public int getCount() {
  return tabTitle.length;
  }
  }*/
  }

 其中,主要部分是Fragment需要重写OnAttach方法,将接口对象实例化,同时在Activity要实现对应接口的方法,在该方法中实现你想要的功能,这样就可以由Fragment灵活交互FragmentActivity中的内容与控件了

  同理,FragmentActivity想要交互对应的Fragment也需要重写FragmentActivity的OnAttachFragment方法,同时在
  Fragment中实现对应接口的方法,在该方法中实现你想要的功能,这样就可以由FragmentActivity灵活交互Fragment中的内容与控件了 (主要看没有注释的部分)
  其实,交互的思路都是一样的,全都是通过一个公共的接口调用,在对应的地方实现。

上一篇:Can you find it?(二分 二分+STL set map)


下一篇:java读取网页