FragmentActivity与Fragment两者交互方法简介
在Android4.0后很多时候我们会大量使用到Fragment,Fragment与Activity的交互应该来说是非常重要的,但目前很多实例方法都只介绍了Fragment与Activity交互的方法,没有Activity与Fragment交互的方法,下面我来把解决的思路记录如下。
1.首先我需要定义一个公共接口,用于将Fragment与FragmentActivity中的控件进行交互
Fragment中实现对应接口的方法,在该方法中实现你想要的功能,这样就可以由FragmentActivity灵活交互Fragment中的内容与控件了 (主要看没有注释的部分)
其实,交互的思路都是一样的,全都是通过一个公共的接口调用,在对应的地方实现。
1.首先我需要定义一个公共接口,用于将Fragment与FragmentActivity中的控件进行交互
- public interface IBtnCallListener {
- public void transfermsg();
- }
public interface IBtnCallListener { public void transfermsg(); }
2.当fragment中的Button控件需要与FragmentActivity中的Button控件交互时,在Fragment对应的子类中定义
- 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传输过来的信息");
- }
- }
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中对应相应
- 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;
- }
- }*/
- }
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中的内容与控件了 (主要看没有注释的部分)
其实,交互的思路都是一样的,全都是通过一个公共的接口调用,在对应的地方实现。