How to add dynamic fragment tab items












6















I want to add dynamic tab items. I have a fragment which is FragmentOne and it has a TextView. I'm trying create FragmentOne in foreach and add to tabs. I tested code which is in setupViewPager but it doesn't work. How can I edit TextView which in fragments?



if I remove this lines it works but contents of fragment always show default that = "TAB ONE". I want to edit all TextView which is in fragments that created at run time;



View view = fView.getView();

TextView txtTabItemNumber = (TextView)view.findViewById(R.id.txtTabItemNumber);
txtTabItemNumber.setText("TAB " + i);


DynamicTabsActivity.java



public class DynamicTabsActivity extends AppCompatActivity {

private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dynamic_tabs);


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());
LayoutInflater inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

int count = 10;
for (int i=0; i<count; i++){

OneFragment fView = new OneFragment();
View view = fView.getView();

TextView txtTabItemNumber = (TextView)view.findViewById(R.id.txtTabItemNumber);
txtTabItemNumber.setText("TAB " + i);
adapter.addFrag(fView,"TAB " + i);
}

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 addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}

@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}


activity_dynamic_tabs.xml



<android.support.design.widget.CoordinatorLayout 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.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"/>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>


OneFragment.java



public class OneFragment extends Fragment{

public OneFragment() {
// 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
return inflater.inflate(R.layout.fragment_one, container, false);

}

}


fragment_one.xml



<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="info.androidhive.materialtabs.fragments.OneFragment">

<TextView
android:id="@+id/txtTabItemNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TAB ONE"
android:textSize="40dp"
android:textStyle="bold"
android:layout_centerInParent="true"/>

</RelativeLayout>


enter image description here










share|improve this question

























  • Please add code of OneFragment.

    – avinash
    Dec 22 '16 at 8:48











  • @avinash there is nothing in OneFragment just default onCreateView and onCreate methods. I also edited question

    – Alexander
    Dec 22 '16 at 8:55
















6















I want to add dynamic tab items. I have a fragment which is FragmentOne and it has a TextView. I'm trying create FragmentOne in foreach and add to tabs. I tested code which is in setupViewPager but it doesn't work. How can I edit TextView which in fragments?



if I remove this lines it works but contents of fragment always show default that = "TAB ONE". I want to edit all TextView which is in fragments that created at run time;



View view = fView.getView();

TextView txtTabItemNumber = (TextView)view.findViewById(R.id.txtTabItemNumber);
txtTabItemNumber.setText("TAB " + i);


DynamicTabsActivity.java



public class DynamicTabsActivity extends AppCompatActivity {

private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dynamic_tabs);


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());
LayoutInflater inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

int count = 10;
for (int i=0; i<count; i++){

OneFragment fView = new OneFragment();
View view = fView.getView();

TextView txtTabItemNumber = (TextView)view.findViewById(R.id.txtTabItemNumber);
txtTabItemNumber.setText("TAB " + i);
adapter.addFrag(fView,"TAB " + i);
}

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 addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}

@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}


activity_dynamic_tabs.xml



<android.support.design.widget.CoordinatorLayout 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.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"/>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>


OneFragment.java



public class OneFragment extends Fragment{

public OneFragment() {
// 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
return inflater.inflate(R.layout.fragment_one, container, false);

}

}


fragment_one.xml



<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="info.androidhive.materialtabs.fragments.OneFragment">

<TextView
android:id="@+id/txtTabItemNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TAB ONE"
android:textSize="40dp"
android:textStyle="bold"
android:layout_centerInParent="true"/>

</RelativeLayout>


enter image description here










share|improve this question

























  • Please add code of OneFragment.

    – avinash
    Dec 22 '16 at 8:48











  • @avinash there is nothing in OneFragment just default onCreateView and onCreate methods. I also edited question

    – Alexander
    Dec 22 '16 at 8:55














6












6








6


1






I want to add dynamic tab items. I have a fragment which is FragmentOne and it has a TextView. I'm trying create FragmentOne in foreach and add to tabs. I tested code which is in setupViewPager but it doesn't work. How can I edit TextView which in fragments?



if I remove this lines it works but contents of fragment always show default that = "TAB ONE". I want to edit all TextView which is in fragments that created at run time;



View view = fView.getView();

TextView txtTabItemNumber = (TextView)view.findViewById(R.id.txtTabItemNumber);
txtTabItemNumber.setText("TAB " + i);


DynamicTabsActivity.java



public class DynamicTabsActivity extends AppCompatActivity {

private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dynamic_tabs);


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());
LayoutInflater inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

int count = 10;
for (int i=0; i<count; i++){

OneFragment fView = new OneFragment();
View view = fView.getView();

TextView txtTabItemNumber = (TextView)view.findViewById(R.id.txtTabItemNumber);
txtTabItemNumber.setText("TAB " + i);
adapter.addFrag(fView,"TAB " + i);
}

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 addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}

@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}


activity_dynamic_tabs.xml



<android.support.design.widget.CoordinatorLayout 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.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"/>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>


OneFragment.java



public class OneFragment extends Fragment{

public OneFragment() {
// 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
return inflater.inflate(R.layout.fragment_one, container, false);

}

}


fragment_one.xml



<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="info.androidhive.materialtabs.fragments.OneFragment">

<TextView
android:id="@+id/txtTabItemNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TAB ONE"
android:textSize="40dp"
android:textStyle="bold"
android:layout_centerInParent="true"/>

</RelativeLayout>


enter image description here










share|improve this question
















I want to add dynamic tab items. I have a fragment which is FragmentOne and it has a TextView. I'm trying create FragmentOne in foreach and add to tabs. I tested code which is in setupViewPager but it doesn't work. How can I edit TextView which in fragments?



if I remove this lines it works but contents of fragment always show default that = "TAB ONE". I want to edit all TextView which is in fragments that created at run time;



View view = fView.getView();

TextView txtTabItemNumber = (TextView)view.findViewById(R.id.txtTabItemNumber);
txtTabItemNumber.setText("TAB " + i);


DynamicTabsActivity.java



public class DynamicTabsActivity extends AppCompatActivity {

private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dynamic_tabs);


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());
LayoutInflater inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

int count = 10;
for (int i=0; i<count; i++){

OneFragment fView = new OneFragment();
View view = fView.getView();

TextView txtTabItemNumber = (TextView)view.findViewById(R.id.txtTabItemNumber);
txtTabItemNumber.setText("TAB " + i);
adapter.addFrag(fView,"TAB " + i);
}

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 addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}

@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}


activity_dynamic_tabs.xml



<android.support.design.widget.CoordinatorLayout 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.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"/>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>


OneFragment.java



public class OneFragment extends Fragment{

public OneFragment() {
// 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
return inflater.inflate(R.layout.fragment_one, container, false);

}

}


fragment_one.xml



<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="info.androidhive.materialtabs.fragments.OneFragment">

<TextView
android:id="@+id/txtTabItemNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TAB ONE"
android:textSize="40dp"
android:textStyle="bold"
android:layout_centerInParent="true"/>

</RelativeLayout>


enter image description here







android android-fragments dynamic android-tabs






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 22 '16 at 8:55







Alexander

















asked Dec 22 '16 at 8:00









AlexanderAlexander

5852929




5852929













  • Please add code of OneFragment.

    – avinash
    Dec 22 '16 at 8:48











  • @avinash there is nothing in OneFragment just default onCreateView and onCreate methods. I also edited question

    – Alexander
    Dec 22 '16 at 8:55



















  • Please add code of OneFragment.

    – avinash
    Dec 22 '16 at 8:48











  • @avinash there is nothing in OneFragment just default onCreateView and onCreate methods. I also edited question

    – Alexander
    Dec 22 '16 at 8:55

















Please add code of OneFragment.

– avinash
Dec 22 '16 at 8:48





Please add code of OneFragment.

– avinash
Dec 22 '16 at 8:48













@avinash there is nothing in OneFragment just default onCreateView and onCreate methods. I also edited question

– Alexander
Dec 22 '16 at 8:55





@avinash there is nothing in OneFragment just default onCreateView and onCreate methods. I also edited question

– Alexander
Dec 22 '16 at 8:55












3 Answers
3






active

oldest

votes


















7














The fragment's layout hasn't been created at point that you call findViewById below:



        OneFragment fView = new OneFragment();
View view = fView.getView();

TextView txtTabItemNumber = (TextView)view.findViewById(R.id.txtTabItemNumber);


Following is more typically way this is coded:



public static class OneFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
private int sectionNumber;

public OneFragment() {
}

public static OneFragment newInstance(int sectionNumber) {
OneFragment fragment = new OneFragment();
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) {
View rootView = inflater.inflate(R.layout.fragment_one, container, false);

sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
TextView textView = (TextView) rootView.findViewById(R.id.txtTabItemNumber);
textView.setText("TAB " + sectionNumber);
return rootView;
}
}


you might also want to move fragment creation in to adapter...for example:



    public Fragment getItem(int position) {
return OneFragment.newInstance(position + 1);
}





share|improve this answer































    0














    Try this,



      LinearLayout  main = new LinearLayout(this);
    main.setOrientation(LinearLayout.VERTICAL);
    TextView textView = new TextView(this);
    textView .setText("TAB " + i);
    main .addView(textView );





    share|improve this answer



















    • 1





      I suppose you got the question wrong

      – Alexander
      Dec 22 '16 at 8:41



















    0














    After trying for long...I came up with the following solution:
    DynamicTabsActivity is my main activity, looks like this:



    public class DynamicTabsActivity extends AppCompatActivity {
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private ViewPagerAdapter viewPagerAdapter;

    private int noOfTabs = 10;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dynamic_tabs);

    viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), noOfTabs);
    viewPager = findViewById(R.id.viewpager);
    viewPager.setAdapter(viewPagerAdapter);

    tabLayout = findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    }

    }


    My fragment looks like this:



    public class DynamicFragment extends Fragment {

    private static final String ARG_SECTION_NUMBER = "section_number";
    private int sectionNumber;


    public DynamicFragment() {
    // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    sectionNumber = getArguments() != null ? getArguments().getInt(ARG_SECTION_NUMBER) : 1;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_dynamic, container, false);

    TextView textView = view.findViewById(R.id.txtTabItemNumber);
    textView.setText("TAB " + sectionNumber);


    return view;
    }

    public static DynamicFragment newInstance(int sectionNumber) {
    DynamicFragment fragment = new DynamicFragment();
    Bundle args = new Bundle();
    args.putInt(ARG_SECTION_NUMBER, sectionNumber);
    fragment.setArguments(args);
    return fragment;
    }
    }


    My ViewPager Class looks like this:



    public class ViewPagerAdapter extends FragmentStatePagerAdapter {
    private int noOfItems;

    public ViewPagerAdapter(FragmentManager fm, int noOfItems) {
    super(fm);
    this.noOfItems = noOfItems;
    }

    @Override
    public Fragment getItem(int position) {
    return DynamicFragment.newInstance(position + 1);
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
    return "TAB "+(position+1);
    }
    }


    DynamicTabsActivity layout:



    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DynamicTabsActivity">

    <android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:layout_scrollFlags="scroll|enterAlways"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    <android.support.design.widget.TabLayout
    android:id="@+id/tabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabMode="scrollable"/>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    </android.support.constraint.ConstraintLayout>


    Fragment layout:



    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DynamicFragment">

    <TextView
    android:id="@+id/txtTabItemNumber"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="TAB ONE"
    android:textSize="40dp"
    android:textStyle="bold" />

    </RelativeLayout>


    Hope it helps...






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f41278339%2fhow-to-add-dynamic-fragment-tab-items%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      7














      The fragment's layout hasn't been created at point that you call findViewById below:



              OneFragment fView = new OneFragment();
      View view = fView.getView();

      TextView txtTabItemNumber = (TextView)view.findViewById(R.id.txtTabItemNumber);


      Following is more typically way this is coded:



      public static class OneFragment extends Fragment {
      private static final String ARG_SECTION_NUMBER = "section_number";
      private int sectionNumber;

      public OneFragment() {
      }

      public static OneFragment newInstance(int sectionNumber) {
      OneFragment fragment = new OneFragment();
      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) {
      View rootView = inflater.inflate(R.layout.fragment_one, container, false);

      sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
      TextView textView = (TextView) rootView.findViewById(R.id.txtTabItemNumber);
      textView.setText("TAB " + sectionNumber);
      return rootView;
      }
      }


      you might also want to move fragment creation in to adapter...for example:



          public Fragment getItem(int position) {
      return OneFragment.newInstance(position + 1);
      }





      share|improve this answer




























        7














        The fragment's layout hasn't been created at point that you call findViewById below:



                OneFragment fView = new OneFragment();
        View view = fView.getView();

        TextView txtTabItemNumber = (TextView)view.findViewById(R.id.txtTabItemNumber);


        Following is more typically way this is coded:



        public static class OneFragment extends Fragment {
        private static final String ARG_SECTION_NUMBER = "section_number";
        private int sectionNumber;

        public OneFragment() {
        }

        public static OneFragment newInstance(int sectionNumber) {
        OneFragment fragment = new OneFragment();
        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) {
        View rootView = inflater.inflate(R.layout.fragment_one, container, false);

        sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
        TextView textView = (TextView) rootView.findViewById(R.id.txtTabItemNumber);
        textView.setText("TAB " + sectionNumber);
        return rootView;
        }
        }


        you might also want to move fragment creation in to adapter...for example:



            public Fragment getItem(int position) {
        return OneFragment.newInstance(position + 1);
        }





        share|improve this answer


























          7












          7








          7







          The fragment's layout hasn't been created at point that you call findViewById below:



                  OneFragment fView = new OneFragment();
          View view = fView.getView();

          TextView txtTabItemNumber = (TextView)view.findViewById(R.id.txtTabItemNumber);


          Following is more typically way this is coded:



          public static class OneFragment extends Fragment {
          private static final String ARG_SECTION_NUMBER = "section_number";
          private int sectionNumber;

          public OneFragment() {
          }

          public static OneFragment newInstance(int sectionNumber) {
          OneFragment fragment = new OneFragment();
          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) {
          View rootView = inflater.inflate(R.layout.fragment_one, container, false);

          sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
          TextView textView = (TextView) rootView.findViewById(R.id.txtTabItemNumber);
          textView.setText("TAB " + sectionNumber);
          return rootView;
          }
          }


          you might also want to move fragment creation in to adapter...for example:



              public Fragment getItem(int position) {
          return OneFragment.newInstance(position + 1);
          }





          share|improve this answer













          The fragment's layout hasn't been created at point that you call findViewById below:



                  OneFragment fView = new OneFragment();
          View view = fView.getView();

          TextView txtTabItemNumber = (TextView)view.findViewById(R.id.txtTabItemNumber);


          Following is more typically way this is coded:



          public static class OneFragment extends Fragment {
          private static final String ARG_SECTION_NUMBER = "section_number";
          private int sectionNumber;

          public OneFragment() {
          }

          public static OneFragment newInstance(int sectionNumber) {
          OneFragment fragment = new OneFragment();
          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) {
          View rootView = inflater.inflate(R.layout.fragment_one, container, false);

          sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
          TextView textView = (TextView) rootView.findViewById(R.id.txtTabItemNumber);
          textView.setText("TAB " + sectionNumber);
          return rootView;
          }
          }


          you might also want to move fragment creation in to adapter...for example:



              public Fragment getItem(int position) {
          return OneFragment.newInstance(position + 1);
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Dec 22 '16 at 8:49









          John O'ReillyJohn O'Reilly

          5,51431831




          5,51431831

























              0














              Try this,



                LinearLayout  main = new LinearLayout(this);
              main.setOrientation(LinearLayout.VERTICAL);
              TextView textView = new TextView(this);
              textView .setText("TAB " + i);
              main .addView(textView );





              share|improve this answer



















              • 1





                I suppose you got the question wrong

                – Alexander
                Dec 22 '16 at 8:41
















              0














              Try this,



                LinearLayout  main = new LinearLayout(this);
              main.setOrientation(LinearLayout.VERTICAL);
              TextView textView = new TextView(this);
              textView .setText("TAB " + i);
              main .addView(textView );





              share|improve this answer



















              • 1





                I suppose you got the question wrong

                – Alexander
                Dec 22 '16 at 8:41














              0












              0








              0







              Try this,



                LinearLayout  main = new LinearLayout(this);
              main.setOrientation(LinearLayout.VERTICAL);
              TextView textView = new TextView(this);
              textView .setText("TAB " + i);
              main .addView(textView );





              share|improve this answer













              Try this,



                LinearLayout  main = new LinearLayout(this);
              main.setOrientation(LinearLayout.VERTICAL);
              TextView textView = new TextView(this);
              textView .setText("TAB " + i);
              main .addView(textView );






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Dec 22 '16 at 8:32









              santosh kumarsantosh kumar

              2,1831721




              2,1831721








              • 1





                I suppose you got the question wrong

                – Alexander
                Dec 22 '16 at 8:41














              • 1





                I suppose you got the question wrong

                – Alexander
                Dec 22 '16 at 8:41








              1




              1





              I suppose you got the question wrong

              – Alexander
              Dec 22 '16 at 8:41





              I suppose you got the question wrong

              – Alexander
              Dec 22 '16 at 8:41











              0














              After trying for long...I came up with the following solution:
              DynamicTabsActivity is my main activity, looks like this:



              public class DynamicTabsActivity extends AppCompatActivity {
              private TabLayout tabLayout;
              private ViewPager viewPager;
              private ViewPagerAdapter viewPagerAdapter;

              private int noOfTabs = 10;

              @Override
              protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_dynamic_tabs);

              viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), noOfTabs);
              viewPager = findViewById(R.id.viewpager);
              viewPager.setAdapter(viewPagerAdapter);

              tabLayout = findViewById(R.id.tabs);
              tabLayout.setupWithViewPager(viewPager);
              }

              }


              My fragment looks like this:



              public class DynamicFragment extends Fragment {

              private static final String ARG_SECTION_NUMBER = "section_number";
              private int sectionNumber;


              public DynamicFragment() {
              // Required empty public constructor
              }

              @Override
              public void onCreate(@Nullable Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              sectionNumber = getArguments() != null ? getArguments().getInt(ARG_SECTION_NUMBER) : 1;
              }

              @Override
              public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
              // Inflate the layout for this fragment
              View view = inflater.inflate(R.layout.fragment_dynamic, container, false);

              TextView textView = view.findViewById(R.id.txtTabItemNumber);
              textView.setText("TAB " + sectionNumber);


              return view;
              }

              public static DynamicFragment newInstance(int sectionNumber) {
              DynamicFragment fragment = new DynamicFragment();
              Bundle args = new Bundle();
              args.putInt(ARG_SECTION_NUMBER, sectionNumber);
              fragment.setArguments(args);
              return fragment;
              }
              }


              My ViewPager Class looks like this:



              public class ViewPagerAdapter extends FragmentStatePagerAdapter {
              private int noOfItems;

              public ViewPagerAdapter(FragmentManager fm, int noOfItems) {
              super(fm);
              this.noOfItems = noOfItems;
              }

              @Override
              public Fragment getItem(int position) {
              return DynamicFragment.newInstance(position + 1);
              }

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

              @Override
              public CharSequence getPageTitle(int position) {
              return "TAB "+(position+1);
              }
              }


              DynamicTabsActivity layout:



              <?xml version="1.0" encoding="utf-8"?>
              <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              tools:context=".DynamicTabsActivity">

              <android.support.design.widget.AppBarLayout
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

              <android.support.v7.widget.Toolbar
              android:id="@+id/toolbar"
              android:layout_width="match_parent"
              android:layout_height="?attr/actionBarSize"
              android:background="?attr/colorPrimary"
              app:layout_scrollFlags="scroll|enterAlways"
              app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

              <android.support.design.widget.TabLayout
              android:id="@+id/tabs"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              app:tabMode="scrollable"/>
              </android.support.design.widget.AppBarLayout>

              <android.support.v4.view.ViewPager
              android:id="@+id/viewpager"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              app:layout_behavior="@string/appbar_scrolling_view_behavior" />

              </android.support.constraint.ConstraintLayout>


              Fragment layout:



              <?xml version="1.0" encoding="utf-8"?>
              <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              tools:context=".DynamicFragment">

              <TextView
              android:id="@+id/txtTabItemNumber"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_centerInParent="true"
              android:text="TAB ONE"
              android:textSize="40dp"
              android:textStyle="bold" />

              </RelativeLayout>


              Hope it helps...






              share|improve this answer




























                0














                After trying for long...I came up with the following solution:
                DynamicTabsActivity is my main activity, looks like this:



                public class DynamicTabsActivity extends AppCompatActivity {
                private TabLayout tabLayout;
                private ViewPager viewPager;
                private ViewPagerAdapter viewPagerAdapter;

                private int noOfTabs = 10;

                @Override
                protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_dynamic_tabs);

                viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), noOfTabs);
                viewPager = findViewById(R.id.viewpager);
                viewPager.setAdapter(viewPagerAdapter);

                tabLayout = findViewById(R.id.tabs);
                tabLayout.setupWithViewPager(viewPager);
                }

                }


                My fragment looks like this:



                public class DynamicFragment extends Fragment {

                private static final String ARG_SECTION_NUMBER = "section_number";
                private int sectionNumber;


                public DynamicFragment() {
                // Required empty public constructor
                }

                @Override
                public void onCreate(@Nullable Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                sectionNumber = getArguments() != null ? getArguments().getInt(ARG_SECTION_NUMBER) : 1;
                }

                @Override
                public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
                // Inflate the layout for this fragment
                View view = inflater.inflate(R.layout.fragment_dynamic, container, false);

                TextView textView = view.findViewById(R.id.txtTabItemNumber);
                textView.setText("TAB " + sectionNumber);


                return view;
                }

                public static DynamicFragment newInstance(int sectionNumber) {
                DynamicFragment fragment = new DynamicFragment();
                Bundle args = new Bundle();
                args.putInt(ARG_SECTION_NUMBER, sectionNumber);
                fragment.setArguments(args);
                return fragment;
                }
                }


                My ViewPager Class looks like this:



                public class ViewPagerAdapter extends FragmentStatePagerAdapter {
                private int noOfItems;

                public ViewPagerAdapter(FragmentManager fm, int noOfItems) {
                super(fm);
                this.noOfItems = noOfItems;
                }

                @Override
                public Fragment getItem(int position) {
                return DynamicFragment.newInstance(position + 1);
                }

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

                @Override
                public CharSequence getPageTitle(int position) {
                return "TAB "+(position+1);
                }
                }


                DynamicTabsActivity layout:



                <?xml version="1.0" encoding="utf-8"?>
                <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app="http://schemas.android.com/apk/res-auto"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:context=".DynamicTabsActivity">

                <android.support.design.widget.AppBarLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

                <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:layout_scrollFlags="scroll|enterAlways"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

                <android.support.design.widget.TabLayout
                android:id="@+id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:tabMode="scrollable"/>
                </android.support.design.widget.AppBarLayout>

                <android.support.v4.view.ViewPager
                android:id="@+id/viewpager"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:layout_behavior="@string/appbar_scrolling_view_behavior" />

                </android.support.constraint.ConstraintLayout>


                Fragment layout:



                <?xml version="1.0" encoding="utf-8"?>
                <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:context=".DynamicFragment">

                <TextView
                android:id="@+id/txtTabItemNumber"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:text="TAB ONE"
                android:textSize="40dp"
                android:textStyle="bold" />

                </RelativeLayout>


                Hope it helps...






                share|improve this answer


























                  0












                  0








                  0







                  After trying for long...I came up with the following solution:
                  DynamicTabsActivity is my main activity, looks like this:



                  public class DynamicTabsActivity extends AppCompatActivity {
                  private TabLayout tabLayout;
                  private ViewPager viewPager;
                  private ViewPagerAdapter viewPagerAdapter;

                  private int noOfTabs = 10;

                  @Override
                  protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.activity_dynamic_tabs);

                  viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), noOfTabs);
                  viewPager = findViewById(R.id.viewpager);
                  viewPager.setAdapter(viewPagerAdapter);

                  tabLayout = findViewById(R.id.tabs);
                  tabLayout.setupWithViewPager(viewPager);
                  }

                  }


                  My fragment looks like this:



                  public class DynamicFragment extends Fragment {

                  private static final String ARG_SECTION_NUMBER = "section_number";
                  private int sectionNumber;


                  public DynamicFragment() {
                  // Required empty public constructor
                  }

                  @Override
                  public void onCreate(@Nullable Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  sectionNumber = getArguments() != null ? getArguments().getInt(ARG_SECTION_NUMBER) : 1;
                  }

                  @Override
                  public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
                  // Inflate the layout for this fragment
                  View view = inflater.inflate(R.layout.fragment_dynamic, container, false);

                  TextView textView = view.findViewById(R.id.txtTabItemNumber);
                  textView.setText("TAB " + sectionNumber);


                  return view;
                  }

                  public static DynamicFragment newInstance(int sectionNumber) {
                  DynamicFragment fragment = new DynamicFragment();
                  Bundle args = new Bundle();
                  args.putInt(ARG_SECTION_NUMBER, sectionNumber);
                  fragment.setArguments(args);
                  return fragment;
                  }
                  }


                  My ViewPager Class looks like this:



                  public class ViewPagerAdapter extends FragmentStatePagerAdapter {
                  private int noOfItems;

                  public ViewPagerAdapter(FragmentManager fm, int noOfItems) {
                  super(fm);
                  this.noOfItems = noOfItems;
                  }

                  @Override
                  public Fragment getItem(int position) {
                  return DynamicFragment.newInstance(position + 1);
                  }

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

                  @Override
                  public CharSequence getPageTitle(int position) {
                  return "TAB "+(position+1);
                  }
                  }


                  DynamicTabsActivity layout:



                  <?xml version="1.0" encoding="utf-8"?>
                  <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  xmlns:app="http://schemas.android.com/apk/res-auto"
                  xmlns:tools="http://schemas.android.com/tools"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  tools:context=".DynamicTabsActivity">

                  <android.support.design.widget.AppBarLayout
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

                  <android.support.v7.widget.Toolbar
                  android:id="@+id/toolbar"
                  android:layout_width="match_parent"
                  android:layout_height="?attr/actionBarSize"
                  android:background="?attr/colorPrimary"
                  app:layout_scrollFlags="scroll|enterAlways"
                  app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

                  <android.support.design.widget.TabLayout
                  android:id="@+id/tabs"
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  app:tabMode="scrollable"/>
                  </android.support.design.widget.AppBarLayout>

                  <android.support.v4.view.ViewPager
                  android:id="@+id/viewpager"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  app:layout_behavior="@string/appbar_scrolling_view_behavior" />

                  </android.support.constraint.ConstraintLayout>


                  Fragment layout:



                  <?xml version="1.0" encoding="utf-8"?>
                  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  xmlns:tools="http://schemas.android.com/tools"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  tools:context=".DynamicFragment">

                  <TextView
                  android:id="@+id/txtTabItemNumber"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:layout_centerInParent="true"
                  android:text="TAB ONE"
                  android:textSize="40dp"
                  android:textStyle="bold" />

                  </RelativeLayout>


                  Hope it helps...






                  share|improve this answer













                  After trying for long...I came up with the following solution:
                  DynamicTabsActivity is my main activity, looks like this:



                  public class DynamicTabsActivity extends AppCompatActivity {
                  private TabLayout tabLayout;
                  private ViewPager viewPager;
                  private ViewPagerAdapter viewPagerAdapter;

                  private int noOfTabs = 10;

                  @Override
                  protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.activity_dynamic_tabs);

                  viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), noOfTabs);
                  viewPager = findViewById(R.id.viewpager);
                  viewPager.setAdapter(viewPagerAdapter);

                  tabLayout = findViewById(R.id.tabs);
                  tabLayout.setupWithViewPager(viewPager);
                  }

                  }


                  My fragment looks like this:



                  public class DynamicFragment extends Fragment {

                  private static final String ARG_SECTION_NUMBER = "section_number";
                  private int sectionNumber;


                  public DynamicFragment() {
                  // Required empty public constructor
                  }

                  @Override
                  public void onCreate(@Nullable Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  sectionNumber = getArguments() != null ? getArguments().getInt(ARG_SECTION_NUMBER) : 1;
                  }

                  @Override
                  public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
                  // Inflate the layout for this fragment
                  View view = inflater.inflate(R.layout.fragment_dynamic, container, false);

                  TextView textView = view.findViewById(R.id.txtTabItemNumber);
                  textView.setText("TAB " + sectionNumber);


                  return view;
                  }

                  public static DynamicFragment newInstance(int sectionNumber) {
                  DynamicFragment fragment = new DynamicFragment();
                  Bundle args = new Bundle();
                  args.putInt(ARG_SECTION_NUMBER, sectionNumber);
                  fragment.setArguments(args);
                  return fragment;
                  }
                  }


                  My ViewPager Class looks like this:



                  public class ViewPagerAdapter extends FragmentStatePagerAdapter {
                  private int noOfItems;

                  public ViewPagerAdapter(FragmentManager fm, int noOfItems) {
                  super(fm);
                  this.noOfItems = noOfItems;
                  }

                  @Override
                  public Fragment getItem(int position) {
                  return DynamicFragment.newInstance(position + 1);
                  }

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

                  @Override
                  public CharSequence getPageTitle(int position) {
                  return "TAB "+(position+1);
                  }
                  }


                  DynamicTabsActivity layout:



                  <?xml version="1.0" encoding="utf-8"?>
                  <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  xmlns:app="http://schemas.android.com/apk/res-auto"
                  xmlns:tools="http://schemas.android.com/tools"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  tools:context=".DynamicTabsActivity">

                  <android.support.design.widget.AppBarLayout
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

                  <android.support.v7.widget.Toolbar
                  android:id="@+id/toolbar"
                  android:layout_width="match_parent"
                  android:layout_height="?attr/actionBarSize"
                  android:background="?attr/colorPrimary"
                  app:layout_scrollFlags="scroll|enterAlways"
                  app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

                  <android.support.design.widget.TabLayout
                  android:id="@+id/tabs"
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  app:tabMode="scrollable"/>
                  </android.support.design.widget.AppBarLayout>

                  <android.support.v4.view.ViewPager
                  android:id="@+id/viewpager"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  app:layout_behavior="@string/appbar_scrolling_view_behavior" />

                  </android.support.constraint.ConstraintLayout>


                  Fragment layout:



                  <?xml version="1.0" encoding="utf-8"?>
                  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  xmlns:tools="http://schemas.android.com/tools"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  tools:context=".DynamicFragment">

                  <TextView
                  android:id="@+id/txtTabItemNumber"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:layout_centerInParent="true"
                  android:text="TAB ONE"
                  android:textSize="40dp"
                  android:textStyle="bold" />

                  </RelativeLayout>


                  Hope it helps...







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 20 '18 at 9:48









                  BenBen

                  614




                  614






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f41278339%2fhow-to-add-dynamic-fragment-tab-items%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      MongoDB - Not Authorized To Execute Command

                      How to fix TextFormField cause rebuild widget in Flutter

                      Npm cannot find a required file even through it is in the searched directory