Passing data from Activity with ViewPager its to Fragments - android

I researched a lot and found no solution for my case.
This is my Activity:
public class ProfileActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
//region FindViews
toolbar = (Toolbar) findViewById(R.id.toolbar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
tabLayout = (PagerSlidingTabStrip) findViewById(R.id.tabs);
//endregion
//region ViewPager
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setupViewPager(viewPager);
viewPager.setOffscreenPageLimit(5);
// tabLayout.setupWithViewPager(viewPager);
tabLayout.setViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
switch (position) {
case 0:
changeColor(ContextCompat.getColor(getApplicationContext(), R.color.theme_red_primary));
break;
case 1:
changeColor(ContextCompat.getColor(getApplicationContext(), R.color.theme_yellow_primary));
break;
case 2:
changeColor(ContextCompat.getColor(getApplicationContext(), R.color.theme_green_primary));
break;
case 3:
changeColor(ContextCompat.getColor(getApplicationContext(), R.color.theme_blue_primary));
break;
case 4:
changeColor(ContextCompat.getColor(getApplicationContext(), R.color.theme_black_primary));
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
//endregion
extrasForFragment = new Bundle();
extrasForFragment.putInt("name", 3);
//region Get Extras from Intent
extras = getIntent().getExtras();
if (extras != null) {
userID = extras.getInt(StaticVariables.INTENT_USERID, -1);
Log.e("ISER", "dd " + userID);
OverViewFragment.newInstance().setArguments(extrasForFragment);
}
//endregion
setTitle("");
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(OverViewFragment.newInstance(), getString(R.string.overview));
adapter.addFrag(new Fragment2(), getString(R.string.text));
adapter.addFrag(new Fragment3(), getString(R.string.text));
adapter.addFrag(new Fragment4(), getString(R.string.text));
adapter.addFrag(new Fragment5(), getString(R.string.text));
viewPager.setAdapter(adapter);
}
}
But it won't work.. THis is my fragment:
public class OverViewFragment extends Fragment {
public static OverViewFragment newInstance() {
return new OverViewFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Bundle b = getArguments();
if (b != null) {
Log.e("EXTRAS", "sind: " + b.toString() + " und: " + b.getInt("name", 0));
} else {
Log.e("FAIL", "...");
}
return inflater.inflate(R.layout.fragment_recyclerview, container, false);
}
}
But it didn't work. I tried this:
Send data from activity to fragment in android
and this:
Passing value between activity to fragment on android
But nothing want to work..
I hope for solutions. Thanks for any help!

The only place you call setArguments is at the line OverViewFragment.newInstance().setArguments(extrasForFragment); which is not used in your ViewPager. You want to set the arguments in your setupViewPager method, so like this:
Fragment overviewFrag = OverViewFragment.newInstance();
overviewFrag.setArguments(<args_bundle>);
adapter.addFrag(overviewFrag, getString(R.string.overview));

Related

Not getting current selected Tab position in android tablayout

I am creating a Tab based application where the user can create tabs by clicking a button and can delete the tabs by clicking another button. I implemented this using Tab layout, Fragments and Viewpager.
I am able to get the current tab position when new tab is created by the function setuptablyout function. But when i clicked another tab ie moving to other tabs I am not able to toast the position.
I found that using tabLayout.addOnTabSelectedListener I can get the position, while that doesn't work here.
my Activity Code is:
public class MainActivity extends AppCompatActivity{
TextView textView;
private TabLayout tabLayout;
public static ViewPager viewPager;
public static ViewPagerAdapter adapter;
private ImageView add;
int selectedTabPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.my_viewpager);
tabLayout = (TabLayout) findViewById(R.id.my_tab_layout);
add= (ImageView) findViewById(R.id.imageButtonAdd1);
adapter = new ViewPagerAdapter(getSupportFragmentManager(), MainActivity.this, viewPager, tabLayout);
viewPager.setAdapter(adapter);
createFirstFragment("POS "+adapter.getCount());
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Toast.makeText(getApplicationContext(),"Pos onTabSelected: "+ tabLayout.getSelectedTabPosition(),Toast.LENGTH_SHORT).show();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(adapter.getCount() > 4){
Toast.makeText(MainActivity.this, "Only 5 Tabs allowed", Toast.LENGTH_SHORT).show();
}
else {
Bundle bundle = new Bundle();
bundle.putString("data", "POS "+adapter.getCount());
FragmentChild fragmentChild = new FragmentChild();
fragmentChild.setArguments(bundle);
adapter.addFrag(fragmentChild, "POS "+adapter.getCount());
adapter.notifyDataSetChanged();
if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);
Log.e("adapter.getCount()",String.valueOf(adapter.getCount()));
viewPager.setCurrentItem(adapter.getCount() - 1);
setupTabLayout();
}
}
});
}
public void createFirstFragment(String pagename) {
Bundle bundle = new Bundle();
bundle.putString("data", pagename);
FragmentChild fragmentChild = new FragmentChild();
fragmentChild.setArguments(bundle);
adapter.addFrag(fragmentChild, pagename);
adapter.notifyDataSetChanged();
if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);
Log.e("adapter.getCount()",String.valueOf(adapter.getCount()));
viewPager.setCurrentItem(adapter.getCount() - 1);
setupTabLayout();
}
public void setupTabLayout() {
selectedTabPosition = viewPager.getCurrentItem();
Toast.makeText(MainActivity.this, "selectedTabPosition --> "+selectedTabPosition, Toast.LENGTH_SHORT).show();
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setCustomView(adapter.getTabView(i));
}
}
}
ViewPager class:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final ArrayList<Fragment> mFragmentList = new ArrayList<>();
private final ArrayList<String> mFragmentTitleList = new ArrayList<>();
Context context;
ViewPager viewPager;
TabLayout tabLayout;
int selectedTabPosition;
PreferenceHelper prefs;
private Map<Integer, String> mFragmentTags;
private FragmentManager mFragmentManager;
private boolean doNotifyDataSetChangedOnce = false;
public ViewPagerAdapter(FragmentManager manager, Context context, ViewPager viewPager,
TabLayout tabLayout) {
super(manager);
this.context = context;
this.viewPager = viewPager;
this.tabLayout = tabLayout;
mFragmentTags = new HashMap<Integer, String>();
prefs = new PreferenceHelper(context);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
if (doNotifyDataSetChangedOnce) {
doNotifyDataSetChangedOnce = false;
notifyDataSetChanged();
}
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void removeFrag(int position) {
removeTab(position);
Fragment fragment = mFragmentList.get(position);
mFragmentList.remove(fragment);
mFragmentTitleList.remove(position);
//destroyFragmentView(viewPager, position, fragment);
notifyDataSetChanged();
Log.e("getCount()", String.valueOf(getCount()));
if (getCount() > 0)
tabLayout.setupWithViewPager(viewPager);
setupTabLayout();
}
public View getTabView(final int position) {
View view = LayoutInflater.from(context).inflate(R.layout.custom_tab_item, null);
TextView tabItemName = (TextView) view.findViewById(R.id.textViewTabItemName);
ImageView tabItemAvatar =
(ImageView) view.findViewById(R.id.imageViewTabItemAvatar);
ImageButton remove = (ImageButton) view.findViewById(R.id.imageButtonRemove);
if(getCount() == 1){
remove.setVisibility(View.INVISIBLE);
}
else{
remove.setVisibility(View.VISIBLE);
}
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Remove", "Remove");
if(getCount() != 1){
removeFrag(position);
}
else{
// Toast.makeText("Atleast One Tab is requied")
}
}
});
tabItemName.setText(mFragmentTitleList.get(position));
tabItemName.setTextColor(context.getResources().getColor(android.R.color.background_light));
tabItemAvatar.setImageResource(R.drawable.boy);
return view;
}
public void setupTabLayout() {
selectedTabPosition = viewPager.getCurrentItem();
Toast.makeText(context, "selectedTabPosition --> "+selectedTabPosition, Toast.LENGTH_SHORT).show();
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setCustomView(getTabView(i));
}
}
public void removeTab(int position) {
if (tabLayout.getChildCount() > 0 && tabLayout!=null) {
tabLayout.removeTabAt(position);
prefs.remove("POS"+position);
}
}
/*#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
if (mCurrentFragment != object) {
mCurrentFragment = (Fragment) object;
}
super.setPrimaryItem(container, position, object);
}*/
#Override
public Object instantiateItem(ViewGroup container, int position) {
Object object = super.instantiateItem(container, position);
if (object instanceof Fragment) {
Fragment fragment = (Fragment) object;
String tag = fragment.getTag();
mFragmentTags.put(position, tag);
}
return object;
}
public Fragment getFragment(int position) {
Fragment fragment = null;
String tag = mFragmentTags.get(position);
if (tag != null) {
fragment = mFragmentManager.findFragmentByTag(tag);
}
return fragment;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
I am getting this weird behaviour that whenever I create new tabs the onTabSelected functions are calling multiple time that even when I create 3rd tab onTabslected toast shows Pos onTabSelected: 0,1 and not the just 2nd position which is supposed to be the 2nd position. What can I do to solve this?
My intention is to get some unique tab id so that I can identify each tab separately
you just create the newInstance constructor for creating fragment with arguments
in your FragmentChild
public static FragmentChild newInstance(int page, String title) {
FragmentChild fragmentChild = new FragmentChild ();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentChild.setArguments(args);
return fragmentChild;
}
// Store instance variables based on arguments passed
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("someTitle");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first, container, false);
TextView tvLabel = (TextView) view.findViewById(R.id.tvLabel);
tvLabel.setText(page + " -- " + title);
return view;
}
And then after in adapter class change this.
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
to
#Override
public Fragment getItem(int position) {
return FragmentChild.newInstance(position, "Page # 1");
}
I have not tested this code but, I think this code will help you to get your unique tab id..
test this code and let me know if it works

can i seperate java class files for each pages in viewpager of tab view

I have imported the tabbed activity from android studio.
Under static placeholder fragment i have oncreate view and i have switched cases for each tab and given a seperate layout for each. I want to work in separate java class for each page in tab view. Can i seperate each cases to be in seperate class?
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
int tabNumber= getArguments().getInt(ARG_SECTION_NUMBER);
switch (tabNumber) {
case 1: {
View rootView = inflater.inflate(R.layout.tab1, container, false);
return rootView;
}
case 2: {
View rootView = inflater.inflate(R.layout.tab2, container, false);
return rootView;
}
case 3: {
View rootView = inflater.inflate(R.layout.tab3, container, false);
return rootView;
}
private class DesignDemoPagerAdapter extends FragmentStatePagerAdapter {
public DesignDemoPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
//
if (position == 0) {
BaseFragment f = new SalesBlankTab();
salesStack.get(AppConstant.SALES_REPORT_TAB).push(f);
return f;
} else if (position == 1) {
BaseFragment f = new MemberBlankTab();
salesStack.get(AppConstant.MEMBER_ORDER).push(f);
return f;
} else {
BaseFragment f = new StockBlankTab();//MemberBlankTab,StockBlankTab
salesStack.get(AppConstant.STOCK_MANAGEMENT).push(f);
return f;
}
}
#Override
public int getCount() {
return AppConstant.TAB_COUNT;
}
}
So rishav there is a geItem method which returns variables as super.( ..... )
just return fragment at this place.
#Override
public Fragment getItem(int i)
{ Fragment fragment;
switch(i){
case 0: fragment = new MyFragment1();
break;
case 1: fragment = new MyFragment2();
break;
case 2:
fragment = new MyFragment3(); break;
default:
throw new IllegalArgumentException("Invalid section number"); }
return fragment; }
You can do something like this (from Android Hive):
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "ONE");
adapter.addFragment(new TwoFragment(), "TWO");
adapter.addFragment(new ThreeFragment(), "THREE");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
for more detail, you can try on this link: http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/

How to pass value from activity to fragment through view pager

I have an activity which uses view pager to switch between fragments. I have three fragments. While switching between these fragments i have to pass a string value to the fragment class to identify which fragment is selected.Because here I am using same fragment class for all the three fragments.
Here is my main activity.
public class mainActivity extends AppCompatActivity {
public String kind, value;
private TabLayout tabLayout;
private ViewPager viewPager;
public FloatingActionButton upload, send;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
upload = (FloatingActionButton) findViewById(R.id.upload_fab);
send = (FloatingActionButton) findViewById(R.id.send_message);
uploadFab.hide();
Intent mIntent = getIntent();
kind = mIntent.getStringExtra("KIND");
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Student student =new Student();
switch (position) {
case 0:
upload.hide();
value = "r";
break;
case 1:
upload.hide();
value = "e";
break;
case 2:
upload.show();
value = "u";
break;
default:
upload.hide();
val = "r";
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new RemainderFragment(), "REMAINDER");
adapter.addFragment(new RemainderFragment(), "EMAIL");
adapter.addFragment(new RemainderFragment(), "UPLOAD");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
here is my fragment class
public class RemainderFragment extends Fragment {
public RemainderEmailFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.raminder_fragment, container, false);
EditText subject = (EditText) rootView.findViewById(R.id.subject);
EditText des = (EditText) rootView.findViewById(R.id.description);
// String value = mainActivity.value
//button to send data
button = activity.send;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//getting details
SendData();
}
});
return rootView;
}
public void SendData() {
//functon
}
I have tried intents and shared preferences to send data. but nothing worked. I have to get the String value in my fragment class. please help.
Please check the below code for sample required changes, I have modified your file and added some code to support your requirement.
Your Activity file
package com.adobe.reader.test;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import com.adobe.reader.R;
public class mainActivity extends AppCompatActivity
{
public String kind, value;
private TabLayout tabLayout;
private ViewPager viewPager;
public FloatingActionButton upload, send;
// Adding adapter
private ViewPagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
upload = (FloatingActionButton) findViewById(R.id.upload_fab);
send = (FloatingActionButton) findViewById(R.id.send_message);
uploadFab.hide();
Intent mIntent = getIntent();
kind = mIntent.getStringExtra("KIND");
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
// Let's say we need to call some method from fragment in the activity
Fragment fragment = getCurrentFragment();
if (Fragment instanceof RemainderFragment)
{
RemainderFragment remainderFragment = (RemainderFragment) fragment;
remainderFragment.setString("Testing string");
}
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Fragment fragment = getCurrentFragment();
if (Fragment instanceof RemainderFragment)
{
RemainderFragment remainderFragment = (RemainderFragment) fragment;
}
Student student =new Student();
switch (position) {
case 0:
upload.hide();
value = "r";
break;
case 1:
upload.hide();
value = "e";
break;
case 2:
upload.show();
value = "u";
break;
default:
upload.hide();
val = "r";
break;
}
remainderFragment.setString(value);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
/**
* This method will give you current fragment used in the viewpager.
* #return
*/
public Fragment getCurrentFragment()
{
Fragment fragment = null;
if (viewPager != null)
{
int currentFragmentIndex = viewPager.getCurrentItem();
if (adapter != null)
{
fragment = adapter.getItem(currentFragmentIndex);
}
}
return fragment;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new RemainderFragment(), "REMAINDER");
adapter.addFragment(new RemainderFragment(), "EMAIL");
adapter.addFragment(new RemainderFragment(), "UPLOAD");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Your Fragment file
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import com.adobe.reader.R;
public class RemainderFragment extends Fragment
{
public String testingString;
public RemainderEmailFragment() {
// Required empty public constructor
}
// Sample method to be called from activity
public void setString(String testStr)
{
testingString = testStr;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.raminder_fragment, container, false);
EditText subject = (EditText) rootView.findViewById(R.id.subject);
EditText des = (EditText) rootView.findViewById(R.id.description);
// String value = mainActivity.value
//button to send data
button = activity.send;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//getting details
SendData();
}
});
return rootView;
}
public void SendData() {
//functon
}

PagerSlidingTabStrip shows wrong ViewPager

I have used fragments for drawer item, each fragments consists of non-fixed tabs.I'm using PagerSlidingTabStrip library for showing tabs.When fragment is initialized it shows 1st ViewPager, which is correct but when I click on 2nd tab it shows up 3rd ViewPager.Likewise the last ViewPager is never shown.
Tab xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dp"
android:textColor="#000000"
android:textSize="#dimen/sp_fifteen"
app:pstsDividerColor="#color/red"
app:pstsIndicatorColor="#color/black"
app:pstsTextAllCaps="true"
app:pstsUnderlineColor="#color/gray" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Adapter class:
private PagerSlidingTabStrip tabStrip;
private Adapter adapter;
public static TowerOneTabs newInstance() {
TowerOneTabs fragment = new TowerOneTabs();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View mView = getActivity().getLayoutInflater().inflate(R.layout.tower_tabs_layout, null);
super.onCreate(savedInstanceState);
ViewPager viewPager = (ViewPager) mView.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabStrip = (PagerSlidingTabStrip) mView.findViewById(R.id.tabs);
tabStrip.setViewPager(viewPager);
tabStrip.setOnPageChangeListener(this);
return mView;
}
#Override
public void onResume() {
super.onResume();
tabStrip.setOnPageChangeListener(this);
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
private void setupViewPager(ViewPager viewPager) {
//Here we have to pass ChildFragmentManager instead of FragmentManager.
adapter = new Adapter(getChildFragmentManager());
adapter.addFragment(TowerOne.newInstance(), getResources().getString(R.string.tower1));
adapter.addFragment(T11.newInstance(), Constants.KEY_T1_1);
adapter.addFragment(T12.newInstance(), Constants.KEY_T1_2);
adapter.addFragment(T13.newInstance(), Constants.KEY_T1_3);
adapter.addFragment(T14.newInstance(), Constants.KEY_T1_4);
adapter.addFragment(T15.newInstance(), Constants.KEY_T1_5);
viewPager.setAdapter(adapter);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
switch (position) {
case 0:
// BaseActivity.getTitleView().setText(Constants.KEY_TOWER_ONE);
break;
case 1:
mCallback.showDialog();
break;
case 2:
mCallback.showDialog();
break;
case 3:
mCallback.showDialog();
break;
case 4:
mCallback.showDialog();
break;
case 5:
mCallback.showDialog();
break;
default:
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
I checked this code and its working. If you want to add extra parameter (like Constant), you can edit the SampleFragmentPagerAdapter's addFragment method.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
//viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager()));
setupViewPager(viewPager);
// Give the PagerSlidingTabStrip the ViewPager
PagerSlidingTabStrip tabsStrip = (PagerSlidingTabStrip) findViewById(R.id.tabs);
// Attach the view pager to the tab strip
tabsStrip.setViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
SampleFragmentPagerAdapter adapter = new SampleFragmentPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "ONE");
adapter.addFragment(new TwoFragment(), "TWO");
viewPager.setAdapter(adapter);
}
public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public SampleFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return mFragmentList.size();
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}

TabLayout with ViewPager not working inside fragment Android

Hi I have a TabLayout and ViewPager inside a fragment. But I can not slide beetween tab to come to child fragment (Working normally when in Activity but not work in fragment).
Here is my code for Tablayout inside fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View inflateView = inflater.inflate(R.layout.fragment_assign_beacon_to_event, container, false);
//Viewpager and TabLayout
viewPager = (ViewPager)inflateView.findViewById(R.id.viewPager);
viewPager.setAdapter(new CustomAdapter(getFragmentManager(), getContext()));
tabLayout = (TabLayout)inflateView.findViewById(R.id.tabLayout);
// Inflate the layout for this fragment
return inflateView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
});
Any here is my Custom Adapter class
private class CustomAdapter extends FragmentPagerAdapter {
private String fragments[] = {"Assign Event", "Manage Event"};
public CustomAdapter(FragmentManager supportFragmentManager, Context applicationContext) {
super(supportFragmentManager);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
// return new AssignEventToBeacon();
return new Test1();
case 1:
return new ManageEventAssigned();
default:
return null;
}
}
#Override
public int getCount() {
return fragments.length;
}
#Override
public CharSequence getPageTitle(int position) {
return fragments[position];
}
}
I doubt i have problem with this line:
viewPager.setAdapter(new CustomAdapter(getFragmentManager(), getContext()));
Anyhelp is much appreciate, thanks
I have done a similar project and here is my code for the fragment :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.outer_fragment, container, false);
setHasOptionsMenu(true);
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
if (viewPager != null) {
setupViewPager(viewPager);
}
Log.v("Layout","Tabs");
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#FFFFFF"));
tabLayout.setTabTextColors(Color.parseColor("#707070"), Color.parseColor("#FFFFFF"));
assert viewPager != null;
tabLayout.setupWithViewPager(viewPager);
return view;
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getChildFragmentManager());
adapter.addFragment(new Tab1Fragment(), "PHOTOS");
adapter.addFragment(new Tab2Fragment(), "HI-FIVES");
viewPager.setAdapter(adapter);
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
You need to use getChildFragmentManager() in Fragment instead of getFragmentManager().
From getChildFragmentManager() documentation
Return a private FragmentManager for placing and managing Fragments
inside of this Fragment.
From getFragmentManager() documentation
Return the FragmentManager for interacting with fragments associated
with this fragment's activity.
In simple words,
Use getChildFragmentManager() for Child Fragments
Use getFragmentManager() for Fragments inside Activity
One can see #this answer for complete code.

Categories

Resources