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>
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);
}
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...
Try this,
LinearLayout main = new LinearLayout(this);
main.setOrientation(LinearLayout.VERTICAL);
TextView textView = new TextView(this);
textView .setText("TAB " + i);
main .addView(textView );
Related
I am trying to create tabs within a fragment. I have a 3 fragments
for example in this fragment named "fragment_home.xml", I want to add 2 tabs to it
here is the xml file :
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".ui.home.HomeFragment">
<TextView
android:id="#+id/text_home"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:textAlignment="center"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Here is the java class with ViewModel for the fragment :
"HomeFragment.java" :
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
homeViewModel =
ViewModelProviders.of(this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.fragment_home, container, false);
final TextView textView = root.findViewById(R.id.text_home);
homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
"HomeViewModel.java" :
public class HomeViewModel extends ViewModel {
private MutableLiveData<String> mText;
public HomeViewModel() {
mText = new MutableLiveData<>();
mText.setValue("This is home fragment");
}
public LiveData<String> getText() {
return mText;
}
}
public class FixturesTabs extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fixtures_new_tabs,container, false);
// Setting ViewPager for each Tabs
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
setupViewPager(viewPager);
// Set Tabs inside Toolbar
TabLayout tabs = (TabLayout) view.findViewById(R.id.result_tabs);
tabs.setupWithViewPager(viewPager);
return view;
}
// Add Fragments to Tabs
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getChildFragmentManager());
adapter.addFragment(new TodaysFixturesFragment(), "Today");
adapter.addFragment(new WeekFixturesFragment(), "Week");
adapter.addFragment(new MonthFixturesFragment(), "Month");
adapter.addFragment(new AllFixturesFragment(), "Month");
adapter.addFragment(new MyTeamsFixturesFragment(), "My Teams");
viewPager.setAdapter(adapter);
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public Adapter(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);
}
}
}
XML named "fixtures_new_tabs.xml" to match the inflated 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"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.design.widget.CoordinatorLayout
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.TabLayout
android:id="#+id/result_tabs"
android:background="#color/grey"
app:tabTextColor="#color/medium_grey"
app:tabSelectedTextColor="#color/colorPrimary"
app:tabIndicatorColor="#color/colorPrimary"
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>
</RelativeLayout>
you can read this
I am trying to add View Pager in Fragment Class. I have tried all stuff.
public class MessageFragment extends android.support.v4.app.Fragment{
private ViewPager viewPager;
private TabLayout tabLayout;
public static MessageFragment newInstance() {
MessageFragment fragment = new MessageFragment();
Log.d("Click", "newInstance: ");
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_message, container, false);
ViewPager viewPager=(ViewPager)view.findViewById(R.id.viewpager);
if(viewPager!=null)
{
setUpViewPager(viewPager);
}
TabLayout tabLayout = (TabLayout)view. findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabTextColors(getResources().getColorStateList(R.color.colorToolbar));
return view;
}
private void setUpViewPager(ViewPager viewPager)
{
Adapter adapter=new Adapter(getActivity().getSupportFragmentManager());
adapter.addFragment(new TabTaskFragment(),"Tasks");
adapter.addFragment(new TabChatFragment(),"Chat");
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);
}
}
}
Here is my xml file, I have added all viewpager code over here
please find
XML FILE:
<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:id="#+id/appbar"
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="wrap_content"
android:visibility="gone"
app:layout_scrollFlags="scroll|enterAlways|snap"
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"
android:background="#color/white"
app:tabIndicatorColor="#color/colorToolbar"
app:tabTextAppearance="#android:style/TextAppearance.Widget.TabWidget"
app:tabTextColor="#color/colorToolbar" />
</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" />
How can I add?
I am not able to fix it.
Tabs will show 1st time, but when the user clicks on any bottom tab than tabs description gone and its show blank screens.
I have tried all stuffs disappointed at last.
Your class file should like this
public class ViewPagerFragment extends Fragment {
ViewPager viewPager;
PagerAdapter mPagerAdapter;
TabLayout tabLayout;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.myLayout, null);
viewPager = (ViewPager) view.findViewById(R.id.transactions_recharge);
mPagerAdapter = new ViewPagerAdapter(getChildFragmentManager(), 7);
viewPager.setAdapter(mPagerAdapter);
tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
return view;
}
class ViewPagerAdapter extends FragmentPagerAdapter {
int pageCount = 0;
String titles[] = {"One", "Two", "Three"};
ViewPagerAdapter(FragmentManager manager, int _pageCount) {
super(manager);
pageCount = _pageCount;
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
//load fragment one
return new FragmentOne();
} else if (position == 1) {
//load fragment two
} else if (position == 2) {
//load fragment three
}
}
#Override
public int getCount() {
return pageCount;
}
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
}
And your XML should me like this.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:id="#+id/content_layout"
android:layout_height="match_parent"
android:background="#color/primary">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="#color/white"
app:tabIndicatorHeight="2dp"
app:tabMode="scrollable" />
<android.support.v4.view.ViewPager
android:id="#+id/transactions_recharge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tabs"
android:background="#android:color/transparent">
</android.support.v4.view.ViewPager>
</RelativeLayout>
I have a problem with my ViewPager and fragments it contains. I have 2 menus (A and B), my homepage is directly A. When I click on a menu B fragment which contains a TabLayout, which contains a ViewPager himself three fragments (each contains a simple TextView with Lorem ipsum).
The 3 fragments of ViewPager are correct but if I click on the menu A and I click again on the menu B I do not have any content. Nothing on the fragments 1 and 2 against with the 3rd still has the text and if I return to fragment 1 reads income (for nothing against the fragment 2).
Here is my code :
Menu B (FragmentTabLayout)
public class TabLayoutFragment extends Fragment {
private static final String ARG_TEXT = "ARG_TEXT";
private static final String ARG_COLOR = "ARG_COLOR";
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
public TabLayoutFragment() {
// Required empty public constructor
}
public static TabLayoutFragment newInstance(String text, int color) {
Bundle args = new Bundle();
args.putString(ARG_TEXT, text);
args.putInt(ARG_COLOR, color);
TabLayoutFragment tabLayoutFragment = new TabLayoutFragment();
tabLayoutFragment.setArguments(args);
return tabLayoutFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_tab_layout, container, false);
toolbar = (Toolbar) view.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
toolbar.setBackgroundColor(getArguments().getInt(ARG_COLOR));
toolbar.setTitle(getArguments().getString(ARG_TEXT));
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setBackgroundColor(getArguments().getInt(ARG_COLOR));
tabLayout.setSelectedTabIndicatorColor(Color.WHITE);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.tab_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
//private final List<TabFragment> mFragmentList = new ArrayList<>();
//private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return TabFragment.newInstance("Fragment 2-1");
case 1:
return TabFragment.newInstance("Fragment 2-2");
case 2:
return TabFragment.newInstance("Fragment 2-3");
default:
return TabFragment.newInstance("Fragment Default");
}
}
#Override
public int getCount() {
//return mFragmentList.size();
return 3;
}
}
}
Fragment in ViewPager :
public class TabFragment extends Fragment {
private static final String ARG_TEXT = "ARG_TEXT";
private TextView tv;
public TabFragment() {
// Required empty public constructor
}
public static TabFragment newInstance(String text) {
Bundle args = new Bundle();
args.putString(ARG_TEXT, text);
TabFragment tabFragment= new TabFragment();
tabFragment.setArguments(args);
return tabFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_tab, container, false);
tv = (TextView) view.findViewById(R.id.tv);
return view;
}
}
Layout FragmentTabLayout :
<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:orientation="vertical">
<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="fixed"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</android.support.design.widget.CoordinatorLayout>
layout tabFragment :
<LinearLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
tools:context="com.application.myapplication.TabFragment">
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
>
<TextView
android:id="#+id/tv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/lorem_ipsum"
/>
</android.support.v4.widget.NestedScrollView>
</LinearLayout>
you can extends your ViewPagerAdapter
FragmentStatePagerAdapter
instead of
FragmentPagerAdapter
I have same issue and it works for me.
In my Opinion the better approach is you should try using childFragmentManager for your nested fragments
Here is the simple example:
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getChildFragmentManager());
viewPager.setAdapter(adapter);
}
Hopefully it will solve your issue.
I'm making an app and the Main Activity has a tablayout connected to a viewpager. This viewpager has three fragments.
I know that the viewpager adapter manages 3 fragments (the correct amount) because I used Logging statements. Also, I use asyncTasks to load data into the fragments and it is done correctly. When the data is loaded, it populates a recyclerview. I used logging statements and I know that each fragment has a recyclerview with 20 entries, which is correct.
But for some reason, my viewpager does not display the fragments, even though when I call getItemCount() on it, I get the right number of fragments.
Can you help me to figure out why the fragments are being created but not displayed?
Thank you.
This is my MainActivity:
public class MovieListActivity extends AppCompatActivity {
public static final String POPULAR = "popular";
public static final String TOP = "top";
public static final String FAVORITES = "favorites";
private static final String QUERY_TYPE = "query type";
private RecyclerView mRecyclerView;
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
private boolean mTwoPane;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
setupTabLayout();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
if (findViewById(R.id.movie_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
}
}
private void setupTabLayout() {
TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
tabLayout.addTab(tabLayout.newTab().setText(POPULAR));
tabLayout.addTab(tabLayout.newTab().setText(TOP));
tabLayout.addTab(tabLayout.newTab().setText(FAVORITES));
List<Fragment> fragments = new ArrayList<>();
for (int i=0;i<3;i++) {
Bundle bundle = new Bundle();
bundle.putInt(QUERY_TYPE, i);
fragments.add(ListFragment
.instantiate(this,ListFragment.class.getName(),bundle));
}
viewPager.setAdapter(new MoviePagerAdapter(getSupportFragmentManager(), fragments));
tabLayout.setupWithViewPager(viewPager);
}
}
This is the fragment that the viewpager should instantiate 3 times:
public class ListFragment extends Fragment {
private static final String QUERY_TYPE = "query type";
public static final int POPULAR = 0;
public static final int HIGHEST_RATED = 1;
public static final int FAVORITES = 2;
private RecyclerView mRecyclerView;
private int mListType;
public ListFragment() {}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
mListType = this.getArguments().getInt(QUERY_TYPE);
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.movie_list,container,false);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.movie_list);
assert mRecyclerView != null;
setupRecyclerView(mRecyclerView);
if (mListType == HIGHEST_RATED || mListType == POPULAR) {
requestMovies();
}
return super.onCreateView(inflater, container, savedInstanceState);
}
private void setupRecyclerView(#NonNull RecyclerView recyclerView) {
recyclerView.setAdapter(new MovieAdapter(getActivity()));
}
void setMovies(Movie[] movies) {
MovieAdapter movieAdapter = (MovieAdapter)mRecyclerView.getAdapter();
movieAdapter.setMovies(movies);
movieAdapter.notifyDataSetChanged();
}
private void requestMovies() {
if (mRecyclerView.getAdapter().getItemCount() == 0) {
new FetchMoviesTask(this).execute(POPULAR);
}
}
}
Pager Adapter:
public class MoviePagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> mFragments;
public MoviePagerAdapter(FragmentManager fm, List<Fragment> mFragments) {
super(fm);
this.mFragments = mFragments;
}
#Override
public Fragment getItem(int position) {
return this.mFragments.get(position);
}
#Override
public int getCount() {
return mFragments==null? 0 : mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case ListFragment.POPULAR:
return MovieListActivity.POPULAR;
case ListFragment.HIGHEST_RATED:
return MovieListActivity.TOP;
case ListFragment.FAVORITES:
return MovieListActivity.FAVORITES;
default:
throw new IllegalArgumentException("Requesting a fragment that doesn't exist");
}
}
}
Just in case: these are the xml files for the activity and fragment:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
android:fitsSystemWindows="true"
tools:context=".MovieListActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="#style/AppTheme.PopupOverlay" />
<android.support.design.widget.TabLayout
android:id="#+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</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.v4.view.ViewPager>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView 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:id="#+id/movie_list"
android:name="com.example.madelenko.app.moviegami.MovieListFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layoutManager="GridLayoutManager"
app:spanCount="2"
tools:context="com.example.madelenko.app.moviegami.MovieListActivity"
tools:listitem="#layout/movie_list_content" />
return your view which you inflate in Fragment,
#Nullable
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.movie_list,container,false);
return rootView ;
}
I want to create multilevel tabs in android. It should follow a multilevel hierarchy, or a nested tabs philosophy as shown in image. Please provide the link or url if necessary.
Use Multiple Layers of Android TabLayout, Refer this. TabLayout is quite customize-able. For e.g. adding tabs, setting divider height, using custom views in tabs.
You should use ViewPager to do so. Below code will help you to make multilevel tabs in android.
view_pager_main.xml
<android.support.design.widget.AppBarLayout 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">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
style="#style/MyCustomTabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabIndicatorColor="#android:color/white"
app:tabIndicatorHeight="3dp"
app:tabMode="fixed"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
</FrameLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white" />
<TextView
android:id="#+id/tvNoPlans"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No Plans Available"
android:textColor="#android:color/black"
android:visibility="gone" />
</android.support.design.widget.AppBarLayout>
view_pager_child.xml
<android.support.design.widget.AppBarLayout 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">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout_child"
style="#style/MyCustomTabLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="center"
app:tabIndicatorColor="#color/btn_background"
app:tabIndicatorHeight="3dp"
app:tabMode="scrollable"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
</FrameLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager_child"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white" />
</android.support.design.widget.AppBarLayout>
ViewPagerMain.java
public class ViewPagerMain extends Fragment {
ViewPager viewpager;
TabLayout tabLayout;
TextView tvNoPlans;
View rootview;
Fragment fr = null;
ArrayList<String> cat_id = new ArrayList<String>();
ArrayList<String> cat_name = new ArrayList<String>();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.view_pager_main, container, false);
tvNoPlans = (TextView) rootview.findViewById(R.id.tvNoPlans);
viewpager = (ViewPager) rootview.findViewById(R.id.viewpager);
viewpager.setOffscreenPageLimit(3);
tabLayout = (TabLayout) rootview.findViewById(R.id.tabLayout);
cat_id.add(0,"1");
cat_id.add(1,"2");
cat_name.add(0,"Parent1");
cat_name.add(1,"Parent2");
setupViewpager(viewpager);
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) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return rootview;
}
public void setupViewpager(ViewPager viewPager) {
ViewpagerAdapter adapter = new ViewpagerAdapter(getChildFragmentManager());
for (int i = 0; i < cat_id.size(); i++) {
Bundle bundle = new Bundle();
bundle.putString("cat_id",cat_id.get(i));
fr = new ViewPagerChild();
fr.setArguments(bundle);
adapter.addFrag(fr, cat_name.get(i));
}
viewPager.setAdapter(adapter);
}
}
ViewPagerChild.java
public class ViewPagerChild extends Fragment {
ViewPager viewPager_child;
TabLayout tabLayout_child;
SharedPreferences preferences;
View rootview;
String cat_id;
ArrayList<String> subcat_id = new ArrayList<String>();
ArrayList<String> subcat_name = new ArrayList<String>();
Bundle bundle;
Fragment fr = null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.view_pager_child, container, false);
preferences = getActivity().getSharedPreferences(Constant.PREF_MAIN, 0);
bundle = getArguments();
cat_id = bundle.getString("cat_id");
viewPager_child = (ViewPager) rootview.findViewById(R.id.viewpager_child);
viewPager_child.setOffscreenPageLimit(10);
tabLayout_child = (TabLayout) rootview.findViewById(R.id.tabLayout_child);
subcat_id.add(0,"1");
subcat_id.add(1, "2");
subcat_name.add(0,"Child1");
subcat_name.add(1,"Child2");
setupViewpagerChild(viewPager_child);
tabLayout_child.post(new Runnable() {
#Override
public void run() {
tabLayout_child.setupWithViewPager(viewPager_child);
}
});
tabLayout_child.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager_child.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return rootview;
}
public void setupViewpagerChild(ViewPager viewPager_child) {
ViewpagerAdapter adapter = new ViewpagerAdapter(getChildFragmentManager());
for (int i = 0; i < subcat_id.size(); i++) {
fr = new TabFragment();
adapter.addFrag(fr, subcat_name.get(i));
}
viewPager_child.setAdapter(adapter);
}
}
ViewpagerAdapter.java
public class ViewpagerAdapter extends FragmentPagerAdapter {
private final List<android.app.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();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
public void addFrag(Fragment fragment,String title){
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
}
tab_fragment.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tv"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="Hello There!!!"/>
</LinearLayout>
TabFragment.java
public class TabFragment extends Fragment {
View rootview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.fragment_tab, container, false);
return rootview;
}
}