Android - TabLayout - Fragments are empty sometimes - android

I have created an app with a Tabbed Activity. I have 3 Tabs and in the first tab I have added a RecyclerView. At first everything works fine. But when I start the app now, the fragments are empty. Even the fragments of the 2nd and 3rd Tabs are empty, where I only placed a TextView. Here is the code from the MainActivity, it is mainly generated from Android Studio, I only added some code to change the Toolbar title and changed some small things:
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Pflege");
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.tab_icon_pflege);
tabLayout.getTabAt(1).setIcon(R.drawable.tab_icon_dokumentation);
tabLayout.getTabAt(2).setIcon(R.drawable.tab_icon_probleme);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
switch(tab.getPosition()) {
case 0:
mViewPager.setCurrentItem(0);
toolbar.setTitle("Pflege");
break;
case 1:
mViewPager.setCurrentItem(1);
toolbar.setTitle("Daten");
break;
case 2:
mViewPager.setCurrentItem(2);
toolbar.setTitle("Probleme");
break;
default:
mViewPager.setCurrentItem(tab.getPosition());
toolbar.setTitle("Pflege");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position){
case 0:
Tab1Pflege tab1 = new Tab1Pflege();
return tab1;
case 1:
Tab2Dokumentation tab2 = new Tab2Dokumentation();
return tab2;
case 2:
Tab3Probleme tab3 = new Tab3Probleme();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Pflege";
case 1:
return "Daten";
case 2:
return "Probleme";
}
return null;
}
}
}
Here is the XML File for the MainActivity. I changed a bit, that the tabs will be placed at the bottom of the screen:
<?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"
tools:context="eis1617.muellerkimmeyer.app.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay"
android:background="#3f84dd">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_above="#+id/tabs" />
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:elevation="80dp"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="56dp"
android:clickable="true"
app:tabGravity="fill"
app:tabIndicatorHeight="0dp"
app:tabMode="fixed"
app:tabBackground="#drawable/tab_color_selector"
android:background="#3f84dd"/>
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
Now here is the fragment for the first tab. It contains the RecyclerView:
public class Tab1Pflege extends Fragment {
private RecyclerView recyclerView;
private RecyclerView.Adapter rvAdapter;
private RecyclerView.LayoutManager rvLayoutManager;
private ArrayList<String> listItems;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1_pflege, container, false);
listItems = new ArrayList<>();
listItems.add("Test1");
listItems.add("Test2");
listItems.add("Test3");
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
rvLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(rvLayoutManager);
rvAdapter = new RvAdapter(listItems);
recyclerView.setAdapter(rvAdapter);
return rootView;
}
}
And here is the XML File for that tab:
<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="eis1617.muellerkimmeyer.app.MainActivity">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recyclerView"
/>
</RelativeLayout>
And here the XML file for the list items. There is a TextView on the left and an ImageView on the right:
<?xml version="1.0" encoding="utf-8"?>
<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:layout_height="50dp"
android:background="?attr/selectableItemBackground">
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/itemTitle"
android:layout_marginLeft="21dp"
android:layout_marginStart="21dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="20sp" />
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/itemImage"
android:layout_marginRight="11dp"
android:layout_marginEnd="11dp"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
And finally here is my Adapter class for the RecyclerView:
public class RvAdapter extends RecyclerView.Adapter<RvAdapter.MyViewHolder> {
ArrayList<String> listItems;
public RvAdapter (ArrayList<String> listItems){
this.listItems = listItems;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_item_layout, null);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.itemTitle.setText(listItems.get(position));
holder.itemImage.setImageResource(R.drawable.ic_keyboard_arrow_right);
}
#Override
public int getItemCount() {
return listItems.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView itemTitle;
ImageView itemImage;
public MyViewHolder(View itemView){
super(itemView);
itemTitle = (TextView) itemView.findViewById(R.id.itemTitle);
itemImage = (ImageView) itemView.findViewById(R.id.itemImage);
}
}
}
I have already tried to replace "extends FragmentPagerAdapter" in MainActivity with "extends FragmentStatePagerAdapter". But the fragments are still empty. Someone know what could be the problem? Sometimes when I change something for example in the XML file for the list items, it works again. But when I restart the app it didnt work anymore. Looks like it is random if it works or not.

Related

Why is my tab layout for android not working?

I am trying to make a tab sliding activity for my app but I am not able to find what is going wrong.
Here is the code for the tab activity:
public class TabActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ViewPager viewPager = findViewById(R.id.container);
viewPager.setAdapter(new SectionsPagerAdapter(getSupportFragmentManager()));
TabLayout tabLayout = findViewById(R.id.tabs);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_tab, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static abstract class LayoutFragment extends Fragment {
private final int layout;
public LayoutFragment(#LayoutRes int layout) {
this.layout = layout;
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(layout, container, false);
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
public static class Fragment1 extends LayoutFragment {
public Fragment1() {
super(R.layout.fragment_one);
}
}
public static class Fragment2 extends Fragment {
public Fragment2() {
super(R.layout.fragment_two);
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
switch (position) {
case 0:
return new Fragment1();
default:
return new Fragment2();
}
}
#Override
public int getCount() {
return 2;
}
}
}
The code is compiling perfectly but the tabs for fragment1 and fragment2 are not appearing at all.
I am not able to figure out what's going wrong and where, I would appreciate any help.
Edit:
Here is my XML code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.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:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/wallpaper"
android:fitsSystemWindows="true"
tools:context=".TabActivity">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_weight="1"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay"
app:title="#string/app_name">
</androidx.appcompat.widget.Toolbar>
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.tabs.TabItem
android:id="#+id/tabItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab1" />
<com.google.android.material.tabs.TabItem
android:id="#+id/tabItem2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab2" />
</com.google.android.material.tabs.TabLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
I think you forget to set up your view pager with tabs try this one.
ViewPager viewPager = findViewById(R.id.container);
viewPager.setAdapter(new SectionsPagerAdapter(getSupportFragmentManager()));
TabLayout tabLayout = findViewById(R.id.tabs);
tablayout.setUpWithViewPager(viewPager);
try this
tabLayout.setupWithViewPager(viewPager);
and remove this lines
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
EDIT
try to using LinearLayout instead of android.support.design.widget.CoordinatorLayout
EDIT
try this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/tab_bg"
app:tabGravity="fill"
app:tabIndicatorHeight="2dp"
app:tabMode="fixed" />
</android.support.design.widget.AppBarLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/colorAccent" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</LinearLayout>
and in activity do this
private void init(){
ViewPager viewPager = v.findViewById(R.id.viewpager);
setupViewPager(viewPager);
TabLayout tabLayout = v.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
TextView tab1 = (TextView) ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_tab, null, false);
TextView tab2 = (TextView) ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_tab, null, false);
tabLayout.getTabAt(0).setCustomView(tab1);
tabLayout.getTabAt(1).setCustomView(tab2);
}
private void setupViewPager(final ViewPager viewPager) {
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getChildFragmentManager());
viewPager.setOffscreenPageLimit(3);
viewPager.setAdapter(viewPagerAdapter);
}
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
if(position == 0) return new Fragment1();
if(position == 1) return new Fragment2();
throw new IllegalStateException("Unexpected position " + position);
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
if(position == 0) return "Fragment 1";
if(position == 1) return "Fragment 2";
throw new IllegalStateException("Unexpected position " + position);
}
}
here is custom_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

Nested Action Bar Tabs(with ViewPager)

I have a project that uses Action Bar Tabs(with ViewPager).
Tabs move really smoothly when swiping between them, but I need to add two sub tabs, in TAB 2, then move to the next tabs or of course back, just like on the Glassdoor or Flipboard.
Please help.
MainActivity
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return Tab1Fragment.newInstance();
case 1:
return Tab2Fragment.newInstance();
default:
return Tab3Fragment.newInstance();
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Tab 1";
case 1:
return "Tab 2";
case 2:
return "Tab 3";
}
return null;
}
}
}
activity_main.xml
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<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/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
Tab2Fragment- where i want to nest SubTab1Fragment and SubTab2Fragment
public class Tab2Fragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
public Tab2Fragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static Tab2Fragment newInstance() {
Tab2Fragment fragment = new Tab2Fragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_tab2, container, false);
}
}
fragment_tab2.xml
<FrameLayout 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="com.r3dm4n.testprojectapp.Tab2Fragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
I figured this out.
I've also posted a demo project on Github
In the MainActivity you need to return a new Fragment for the one you want "nested" like this:
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return Tab1Fragment.newInstance();
case 1:
return new Tab2Fragment();
default:
return Tab3Fragment.newInstance();
}
In TAB2 fragment, where you want the other nested fragments make the following changes:
public class Tab2Fragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tab2, container, false);
ViewPager mViewPager = (ViewPager) view.findViewById(R.id.container_main);
SectionsPagerAdapter mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager());
mViewPager.setAdapter(mSectionsPagerAdapter);
return view;
}
private class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return Nest1Fragment.newInstance(1);
default:
return Nest2Fragment.newInstance(2);
}
}
#Override
public int getCount() {
// Show 4 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Nested 1";
default:
return "Nested 2";
}
}
}
}
fragment_tab2.xml
<android.support.v4.view.ViewPager
android:id="#+id/container_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
app:layout_scrollFlags="scroll|enterAlways">
<android.support.design.widget.TabLayout
android:id="#+id/tabs2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary" />
<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/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
</android.support.v4.view.ViewPager>
Take a look at this answer
It might help
ViewPager nested in ViewPager
Also while adding sub tabs You can add a condition like this in the listener for moving to next tab
if(mPager.getCurrentItem() >=2)
mParentPager.setCurrentItem()=mParentPager.getCurrenItem()+1
This for moving to previous tab
if(mPager.getCurrentItem() ==0)
mParentPager.setCurrentItem()=mParentPager.getCurrenItem()-1

ViewPager does not show anything

There's something wrong with my TabLayout and ViewPager. It does not show anything. Here's my adapter:
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int mNumOfTabs) {
super(fm);
this.mNumOfTabs = mNumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return ChoiceFragment.newInstance("Mobile Games",
R.drawable.ic_stay_current_portrait_white_48dp, "1");
case 1:
return ChoiceFragment.newInstance("Computer Games",
R.drawable.ic_payment_white_48dp, "5");
default: return ChoiceFragment.newInstance("Mobile Games",
R.drawable.ic_stay_current_portrait_white_48dp, "1");
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
#Override
public CharSequence getPageTitle(int position) {
String title;
if (position == 0)
title = "Mobile";
else
title = "Computer";
return title;
}
Here's my TabFragment class:
public class TabGroupFragment extends Fragment {
public TabGroupFragment() {
// Required empty public constructor
}
public static TabGroupFragment newInstance() {
TabGroupFragment fragment = new TabGroupFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tab_group, container, false);
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Mobile"));
tabLayout.addTab(tabLayout.newTab().setText("Computer"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) view.findViewById(R.id.view_pager);
final PagerAdapter adapter = new PagerAdapter(
getActivity().getSupportFragmentManager(),
tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(
new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return view;
}
}
And here's the layout for the above class:
FrameLayout 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"
android:orientation="vertical"
tools:context=".TabGroupFragment">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/utility_white"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:id="#+id/tab_layout" />
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/view_pager"/>
</LinearLayout>
</ScrollView>
I don't see any wrong here. I just followed the tutorial. Let me know what's happening here. Thank you
Thanks #MikeM. it all worked now. I removed the LinearLayout surrounding the TabLayout and ViewPager and changed the FrameLayout to RelativeLayout and they all showed up. Thank you!
<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"
android:orientation="vertical"
tools:context=".TabGroupFragment">
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/utility_white"
android:elevation="6dp"
android:id="#+id/tab_layout" />
<android.support.v4.view.ViewPager
android:layout_below="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/view_pager"/>
</RelativeLayout>

select default tab after app start

i have an android app with an tab activity und three tabs.
This will be create in my Overview.class
In my OverviewPageAdapter.class i get the correct class and layout for each tab content.
I have a Settings Activity where the user can select a default tab, for example -> tab2
this i will save into the sharedpref.
Now i would like to realize, that tab 2 will be shown as start tab.
How can i do this, that tab 2 each time will be shown at first , when i see the Overview Activity ?
Overview.class
public class Overview extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.overview);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.Tab1)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.Tab2)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.Tab3)));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.page_adapter);
final OverviewPageAdapter adapter = new OverviewPageAdapter (getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
/*** SET TAB 2 as START TAB ****/
viewPager.setCurrentItem(2);
/********/
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
OverviewPageAdapter.class
public class OverviewPageAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public OverviewPageAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
OverviewTab1 tab1 = new OverviewTab1();
return tab1;
case 1:
OverviewTab2 tab2 = new OverviewTab();
return tab2;
case 2:
OverviewTab3 tab3 = new OverviewTab3();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
OverviewTab1.class
public class OverviewTab1 extends Fragment {
private View FragementView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
FragementView = inflater.inflate(R.layout.overview_tab1, container, false);
return FragementView;
}
}
OverviewTab2.class
public class OverviewTab2 extends Fragment {
private View FragementView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
FragementView = inflater.inflate(R.layout.overview_tab2, container, false);
return FragementView;
}
}
OverviewTab3.class
public class OverviewTab3 extends Fragment {
private View FragementView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
FragementView = inflater.inflate(R.layout.overview_tab3, container, false);
return FragementView;
}
}
overview_tab1.xml
<RelativeLayout
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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TAB1"
android:id="tvNoData"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:alpha="1"
android:textSize="18sp"
android:textStyle="bold"
android:allowUndo="false" />
overview_tab2.xml
<RelativeLayout
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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TAB2"
android:id="tvNoData"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:alpha="1"
android:textSize="18sp"
android:textStyle="bold"
android:allowUndo="false" />
overview_tab3.xml
<RelativeLayout
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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TAB3"
android:id="tvNoData"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:alpha="1"
android:textSize="18sp"
android:textStyle="bold"
android:allowUndo="false" />
overview.xml
<RelativeLayout
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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<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">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary" />
<android.support.design.widget.TabLayout
android:id="tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/page_adapter"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.design.widget.CoordinatorLayout>
</RelativeLayout>
You can check getTabAt // Set INDEX
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
TabLayout.Tab tab = tabLayout.getTabAt(0); // Count Starts From 0
tab.select();
Edited
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if(position == 2){ // if you want the third page, for example
//Your code here
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});

Why do I can slide to more than two times while I have only two tabs on Android?

I am learning how to use navigation drawer and navigation tab. I created an app that implement a navigation drawer on MainActivity and each item on navigation drawer will replace fragment on MainActivity to the corresponding fragment.
My first fragment provide two navigation tab using SlidingTabLayout and SlidingTabStrip. The other fragments are just a textview.
If I move from the first item to the second item and then back to first item again, my tab still show two tab, but in fact, I can slide more than two times and the content is not shown.
How do I fix this?
What it should be:
After I move to second drawer and then back to first drawer:
What happened after that:
You can see that I can slide more than twice and the content of fragments are not shown.
MainActivity.java
public class MainActivity extends ActionBarActivity {
String titles[] = {"TabsFragment", "TextFragment"};
Fragment fragment[] = {TabsFragment.newInstance(), TextFragment.newInstance()};
RecyclerView mRecyclerView;
RecyclerView.Adapter mAdapter;
RecyclerView.LayoutManager mLayoutManager;
DrawerLayout drawer;
ActionBarDrawerToggle mDrawerToggle;
static View.OnClickListener drawerItemClickListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView);
mRecyclerView.setHasFixedSize(true);
mAdapter = new DrawerAdapter(titles);
drawerItemClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
int selectedPos = mRecyclerView.getChildPosition(v);
drawer.closeDrawers();
getSupportFragmentManager().beginTransaction()
.replace(R.id.main_content, fragment[selectedPos])
.commit();
}
};
mRecyclerView.setAdapter(mAdapter);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this,
drawer,
toolbar,
R.string.open_drawer,
R.string.close_drawer) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
supportInvalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
supportInvalidateOptionsMenu();
}
};
drawer.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.main_content, fragment[0])
.commit();
}
}
}
activity_main.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout">
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:id="#+id/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize" />
<FrameLayout
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/toolbar"/>
</RelativeLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/RecyclerView"
android:layout_width="320dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#ffffff"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</android.support.v4.widget.DrawerLayout>
TabsFragment.java
public class TabsFragment extends Fragment {
public static Fragment newInstance() {
TabsFragment fragment = new TabsFragment();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_tabs, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ViewPager mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
mViewPager.setAdapter(new SamplePagerAdapter(getActivity().getSupportFragmentManager(), getActivity().getApplicationContext()));
SlidingTabLayout mSlidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setDistributeEvenly(true);
mSlidingTabLayout.setViewPager(mViewPager);
}
class SamplePagerAdapter extends FragmentPagerAdapter {
private String[] tabTitles = new String[] {"Tab One", "Tab Two"};
private Context context;
public SamplePagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
android.support.v4.app.Fragment[] fragment = {TabOneFragment.newInstance(), TabTwoFragment.newInstance()};
return fragment[position];
}
}
}
fragment_tabs.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=".TabsFragment">
<android.com.drawertab.SlidingTabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/toolbar" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/sliding_tabs" />
</RelativeLayout>
TabsOneFragment.java
public class TabOneFragment extends Fragment{
public static TabOneFragment newInstance() {
TabOneFragment fragment = new TabOneFragment();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_tab_one, container, false);
}
}
fragment_tabs_one.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center"
android:id="#+id/text"
android:text="TAB ONE" />
</LinearLayout>
TabsTwoFragment.java
public class TabTwoFragment extends Fragment {
public static TabTwoFragment newInstance() {
TabTwoFragment fragment = new TabTwoFragment();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_tab_two, container, false);
}
}
fragment_tabs_two.java
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center"
android:id="#+id/text"
android:text="TAB TWO" />
</LinearLayout>
TextFragment.java
public class TextFragment extends Fragment {
public static Fragment newInstance() {
TextFragment fragment = new TextFragment();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_text, container, false);
}
}
fragment_text.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center"
android:id="#+id/text"
android:text="FRAGMENT TEXT" />
</LinearLayout>
DrawerAdapter.java
public class DrawerAdapter extends RecyclerView.Adapter<DrawerAdapter.ViewHolder> {
private String mNavTitles[];
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView textView;
public ViewHolder(View itemView,int ViewType) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.rowText);
itemView.setOnClickListener(MainActivity.drawerItemClickListener);
}
}
public DrawerAdapter(String[] titles) {
mNavTitles = titles;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.drawer_item_row, parent, false);
ViewHolder vhItem = new ViewHolder(v, viewType);
return vhItem;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.textView.setText(mNavTitles[position]);
}
#Override
public int getItemCount() {
return mNavTitles.length;
}
}
drawer_item_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:clickable="true"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="12dp"
android:paddingTop="4dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/rowText" />
</LinearLayout>
If you are correct about sliding more times than twice, then you need to set the override method getCount correctly (I realize you know). That's the only issue you need to worry about.
private String[] tabTitles = new String[] {"Tab One", "Tab Two"};
...
#Override
public int getCount() {
return tabTitles.length;
}
Note: I declared tabTitles differently as an array of String "String[]", widely accepted. The other style "tabTitles[]" may not work well with its methods like length.
Looking at your code more closely, I suspect objects TabOneFragment and TabTwoFragment is not working well. Normally override getItem returns the same static Fragment. And of course, I do not see that declaration or code for it.
My suggested try is (from your code):
#Override
public android.support.v4.app.Fragment getItem(int position) {
return TabsFragment.newInstance(position);
}
Note: With the above code, I don't see any use for TabOneFragment and TabTwoFragment, referenced in getItem(int position) in SamplePagerAdapter class. The TextView UI in layout fragment_tab_one.xml is only used for the tab texts. For those texts, the override getPageTitle(int position) can be used and is already coded.

Categories

Resources