-2

i followed this article http://www.truiton.com/2015/06/android-tabs-example-fragments-viewpager/ to implement swipe view and it work nice. So now i want to add button on Tab1 and when clicked has to send data to Tab2. I know there is the issue of using interface but honestly i don't know how to add it on these codes and work provide am completely new to the android. so far i have tried my best on these links Communication between SlidingTabLayout tabs, How to pass data from one swipe tab to another? and How can I communicate/pass data through different Fragments with Swipe Tab? but i fail. Any one help please to make it work on every stage , i mean from Tab1 ->Mainactivity->Tab2

thanks alot

Here are the codes after i edit the question

Fragment1

    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);
  }
}

Interface class

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();     
            }


     }

Adapter Class

 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;
}
}
Community
  • 1
  • 1
f2k
  • 99
  • 11

1 Answers1

0

so after posting more code I'm answering:

Implement some FragmentCommunication for both your Fragments:

//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();
    }

}

note this line inside onActivityCreated:

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

this means implemented FragmentCommunication, TAG will be unique key/name of Fragment and whole method is registration of your interface in Activity. so now you have to add registerFragmentCommunication method to your MainActivity and keep reference to passed interfaces, e.g. in HashMap:

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

so now you can access each FragmentCommunication of both fragments from your MainActivity, e.g by using method like this:

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

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

method is public, so Fragments can call it simply like this:

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

this will show Toast with text: "TabFragment2 says: hi!", which was called inside TabFragment1. now you may pass another kind of data as well :)

there is much more methods like communicating through FragmentStatePagerAdapter like here, passing Bundle arguments where fragments are initialized, additional feedback interfaces (e.g. returning true/false when message was passed) etc. Above is just very simplified way, good luck with improving it! :)

Community
  • 1
  • 1
snachmsm
  • 17,866
  • 3
  • 32
  • 74
  • upvote and/or mark as answer my post if it was useful :) good luck! edit: I've edited my answer with proper map init `HashMap()` – snachmsm Nov 18 '16 at 10:09