Thursday, January 28, 2016

Passing Parameters to FragmentPagerItem (SmartTabLayout) in Android

Following is how you can pass parameters to FragmentPageItem in SmartTablayout -

public class HomeActivity extends AppCompatActivity {

  @Override

  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_demo);

 …

    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);

 …
    FragmentPagerItems pages = new FragmentPagerItems(this);

    fragmentPagerItems.add(FragmentPagerItem.of("Tutorial", 
                 ContentFragment.class, ContentFragment.arguments("param1")));

    fragmentPagerItems.add(FragmentPagerItem.of("Programs", 
                 ContentFragment.class, ContentFragment.arguments("param2")));
 
    FragmentPagerItemAdapter adapter = new FragmentPagerItemAdapter(

        getSupportFragmentManager(), pages);

    viewPager.setAdapter(adapter);
 …
  }

}


Here is the relevant code for ContentFragment -

public class ContentFragment extends Fragment {


  //parameter to be passed
  private static final String KEY_PARAM = "key_param";



  public static ContentFragment newInstance(String param) {

    ContentFragment f = new ContentFragment();

    f.setArguments(arguments(param));

    return f;

  }



  public static Bundle arguments(String param) {

    return new Bundler()

            .putString(KEY_PARAM, param)

            .get();

  }
...

  @Override

  public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

    super.onViewCreated(view, savedInstanceState);


    //use KEY_PARAM here
   String paramValue = getArguments().getString(KEY_PARAM);
  } }

1 comment:

  1. Lucky Club Casino Site - Lucky Club UK
    Lucky Club is a well known betting luckyclub site that offers all sorts of live betting events on a daily basis. This site will provide you with some of the most

    ReplyDelete