滑动视图选项卡之间的通信

时间:2016-11-17 06:57:28

标签: android android-layout android-fragments

我按照这篇文章http://www.truiton.com/2015/06/android-tabs-example-fragments-viewpager/来实现滑动视图,效果很好。所以现在我想在Tab1上添加按钮,当点击时必须将数据发送到Tab2。     我知道有使用界面的问题,但说实话,我不知道如何在这些代码上添加它,工作提供了一个全新的android。   到目前为止,我已尽力使用这些链接Communication between SlidingTabLayout tabsHow to pass data from one swipe tab to another?How can I communicate/pass data through different Fragments with Swipe Tab?,但我失败了。  任何人都请帮助它使每个阶段都有效,我的意思是从Tab1 - > Mainactivity-> Tab2

非常感谢

以下是我编辑问题后的代码

片段1

    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;

   public class TabFragment1 extends Fragment implements AdapterView.OnItemSelectedListener{
 Button send;
@Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

     View v= inflater.inflate(R.layout.tab_fragment_1, container, false);
    send=(Button)v.findViewById(R.id.send);
         send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
   // value to be sent to the TabFragment2 on button click
           String value=" My Data";

                }
            });

  return v;
      }

    }

Fragment2

    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;

   public class TabFragment2 extends Fragment {

@Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.tab_fragment_2, container, false);
 //Display value from TabFragment1 
  textview.setText(value);
  }
}

接口类

public Interface FragmentCommunication
  {
  public void printMessage(String message);

  }

MainActivity

 import android.os.Bundle;
 import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;


public class MainActivity extends AppCompatActivity implements FragmentCommunication{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
    tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
    final PagerAdapter adapter = new PagerAdapter
            (getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });
     }
           public void printMessage(String message)
         {
     Toast.makeText(MainActivity.this,message,Toast.LENGTH_LONG).show();     
            }


     }

适配器类

 import android.support.v4.app.Fragment;    
 import android.support.v4.app.FragmentManager;   
 import android.support.v4.app.FragmentStatePagerAdapter;

public class PagerAdapter extends FragmentStatePagerAdapter {
   int mNumOfTabs;

  public PagerAdapter(FragmentManager fm, int NumOfTabs) {
    super(fm);
    this.mNumOfTabs = NumOfTabs;
}

@Override
public Fragment getItem(int position) {

    switch (position) {
        case 0:
            TabFragment1 tab1 = new TabFragment1();
            return tab1;
        case 1:
            TabFragment2 tab2 = new TabFragment2();
            return tab2;
        default:
            return null;
    }
}

@Override
public int getCount() {
    return mNumOfTabs;
}
}

1 个答案:

答案 0 :(得分:0)

所以在发布更多代码后我回答:

FragmentCommunication s:

实施一些Fragment
//public class TabFragment1 extends Fragment implements FragmentCommunication{
public class TabFragment2 extends Fragment implements FragmentCommunication{

    //public static final String TAG="TabFragment1";
    public static final String TAG="TabFragment2";

    ...

    @Override
    public void onActivityCreated (Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);
        if(getActivity() instanceOf MainActivity)
            ((MainActivity) getActivity()).registerFragmentCommunication(
                TAG, this);
    }

    @Override
    public void printMessage(String message){
        Toast.makeText(getActivity(), TAG+" says: "+message,
            Toast.LENGTH_SHORT).show();
    }

}

请注意onActivityCreated内的这一行:

((MainActivity) getActivity()).registerFragmentCommunication(TAG, this);

this表示已实施FragmentCommunicationTAG将是Fragment的唯一键/名称,整个方法是在Activity中注册您的界面。所以现在你必须将registerFragmentCommunication方法添加到MainActivity并继续引用传递的接口,例如在HashMap

HashMap<String, FragmentCommunication> fragmentCommunications =
    new HashMap<String, FragmentCommunication>();
...
public void registerFragmentCommunication(String key, FragmentCommunication fc){
    fragmentCommunications.put(key, fc);
}

现在您可以从FragmentCommunication访问这两个片段中的每个MainActivity,例如使用以下方法:

public void callFragmentCommunication(String key, String msg){
    if(fragmentCommunications.get(key)!=null)
        fragmentCommunications.get(key).printMessage();
}

callFragmentCommunication(TabFragment1.TAG, "hi!");
callFragmentCommunication(TabFragment2.TAG, "hi!");

方法是公开的,因此Fragment可以像这样调用它:

//inside TabFragment1
if(isAdded() && getActivity()!=null && 
    getActivity() instanceOf MainActivity && 
        !getActivity().isFinishing())
    ((MainActivity) getActivity()).callFragmentCommunication(
        TabFragment2.TAG, "hi!");

这将显示Toast文字:&#34; TabFragment2说:hi!&#34;,在TabFragment1内调用。现在你也可以传递另一种数据:)

还有更多方法,例如通过FragmentStatePagerAdapter like herepassing Bundle arguments进行通信,其中片段已初始化,其他反馈接口(例如,在传递消息时返回true / false)等。上面是只是非常简单的方式,改善它的好运! :)