swipe tablayout is not working correctly - java

i am using "compile 'com.android.support:design:25.1.0'" to implement swipe tablayout. My code has no syntax error but due to some logical error it is not working correctly
Problems: 1) when i slide a page it should move on next tab but it slide or move very slowly and go between two tabs
2) when i come back on privious tabs sometime it does not show even any page and sometime it show wrong page e.g on second tabs it shows third page(fragment)
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabLayout tabLayout;
String[] tabs={"SCORES","NEWS","SERIES"};
tabLayout=(TabLayout) findViewById(R.id.cricTabLayout);
tabLayout.addTab(tabLayout.newTab().setText(tabs[0]));
tabLayout.addTab(tabLayout.newTab().setText(tabs[1]));
tabLayout.addTab(tabLayout.newTab().setText(tabs[2]));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setTabTextColors(Color.parseColor("#627179"), Color.parseColor("#BF4A32"));
final ViewPager viewPager=(ViewPager)findViewById(R.id.cricPagerView);
final PageAdapter pageAdapter=new PageAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(pageAdapter);
// new line
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
// viewPager.clearOnPageChangeListeners();
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
// Toast.makeText(MainActivity.this,"Tab changed",Toast.LENGTH_LONG).show();
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
PageAdapter.java
public class PageAdapter extends FragmentStatePagerAdapter {
int numOfTabs;
public PageAdapter(FragmentManager fm, int numOfTabs) {
super(fm);
this.numOfTabs=numOfTabs;
}
public PageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
return new ScoreFragment();
case 1:
return new NewsFragment();
case 2:
return new SeriesFragment();
default: return null;
}
}
#Override
public int getCount() {
return numOfTabs;
}
}
ScoreFragment.java
public class ScoreFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=null;
Toast.makeText(getContext(),"Score",Toast.LENGTH_LONG).show();
return view;
}
}
SeriesFragment.java
public class ScoreFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=null;
Toast.makeText(getContext(),"Score",Toast.LENGTH_LONG).show();
return view;
}
}
NewsFragment.java
public class NewsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=null;
Toast.makeText(getContext(),"News",Toast.LENGTH_LONG).show();
return view;
}
}
MainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<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:id="#+id/activity_news"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.apple.crickapp.MainActivity"
android:layout_marginLeft="0dp">
<android.support.design.widget.TabLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:elevation="8dp"
android:background="#color/colorBlack"
android:minHeight="?attr/actionBarSize"
android:id="#+id/cricTabLayout"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
>
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="#+id/cricPagerView"
android:layout_below="#id/cricTabLayout"
>
</android.support.v4.view.ViewPager>
</RelativeLayout>

Related

Why wont my VerticalViewPager work at the same time as my HorizontalViewPager

So basically I'm trying to make this app have all those pages and you can swipe to change the direction whichever pages you want it to. What I don't understand is that they don't work together it's either one or the other or when I connect them together the app needs to be slided weirdly.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//HorizontalViewPagerAdapter
View background = findViewById(R.id.am_background_view);
ViewPager viewPager = findViewById(R.id.am_view_pager);
HorizontalViewPagerAdapter adapter = new HorizontalViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(1);
}
}
This is my HorizontalViewPager:
public class HorizontalViewPagerAdapter extends FragmentPagerAdapter {
public HorizontalViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return ChatFragment.create();
case 1:
return ControllerFragment.create();
case 2:
return StoryFragment.create();
}
return null;
}
}
My ControllerFragment that is suppose to make it swipe up and down.
public class ControllerFragment extends Fragment {
public static ControllerFragment create() {
return new ControllerFragment();
}
VerticalViewPager verticalViewPager;
VerticalViewPagerAdapter verticalPageAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.vertical, null);
verticalViewPager = view.findViewById(R.id.am_scrollView);
verticalPageAdapter = new VerticalViewPagerAdapter(getChildFragmentManager());
verticalViewPager.setAdapter(verticalPageAdapter);
return inflater.inflate(R.layout.vertical, null);
}
}
public class VerticalViewPagerAdapter extends FragmentPagerAdapter {
public VerticalViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return SettingsFragment.create();
case 1:
return EmptyFragment.create();
case 2:
return ExtrasFragment.create();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
My Empty Fragment
public class EmptyFragment extends Fragment {
public static EmptyFragment create(){
return new EmptyFragment();
}
}
My MainActivity
<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"
tools:context="c.kristofer.jax2.MainActivity">
<View
android:id="#+id/am_background_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/green"/>
<android.support.v4.view.ViewPager
android:id="#+id/am_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
And last of all a fragment for my vertical scroll
<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"
tools:context="c.kristofer.jax2.MainActivity">
<me.kaelaela.verticalviewpager.VerticalViewPager
android:id="#+id/am_scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>

I want to show 3 different fragments for 3 different tabs in view-pager ,Tabbed activity Android

I am very new to android , this time i created a view-pager tabbed activity by looking a video tutorial. the problem or the need is to show 3 different fragments if the user slides the position like tab1(shows first fragment),tab2 (shows second fragment) tab3 (shows third fragment)
Now it is showing one and only fragment for all tabs
this is my adapter class named datafragment
package com.example.jaison.news;
public class datafragment extends Fragment {
View view;
ViewPager viewPager;
TabLayout tabLayout;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view= inflater.inflate(R.layout.sample,container,false);
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
viewPager.setAdapter(new sliderAdapter(getChildFragmentManager()));
tabLayout = (TabLayout) view.findViewById(R.id.sliding_tabs);
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return view;
}
private class sliderAdapter extends FragmentPagerAdapter{
final String tabs[]={"tab1", "tab2","tab3"};
public sliderAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
return tabs[position];
}
}
}
for those who did not get my point , all i need is implement the code something just like this, but i am not sure about this..
switch (position) {
case 0:
//showing first fragment
case 1:
//showing second fragment
case 2:
//showing third fragment
default:
return new Fragment();
}
change your getItem method like this
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position){
case 0:
fragment = new Tab1Fragment();
break;
case 1:
fragment = new Tab2Fragment();
break;
case 2:
fragment = new Tab3Fragment();
break;
}
return fragment;
}
You need to create an instance of your viewPagerAdapter and then add items to it.
Something like this:
ViewPagerAdapter viewpagerAdapter = new ViewPagerAdapter(getChildFragmentManager());
viewPager.setAdapter(viewpagerAdapter);
// then add items to it as you add items to a recyclerview adapter or to any list
viewpagerAdapter.addFragment(new Fragment1(), "title1");
And the custom code for the viewpager Adapter is:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Also since you are new to programming, would advice you to use proper nomenclature, for eg. names of classes always begin with initial letter Uppercase
class ClassName
void methodName
MainActivity
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "ONE");
adapter.addFragment(new TwoFragment(), "TWO");
adapter.addFragment(new ThreeFragment(), "THREE");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
OneFragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/one"
android:textSize="40dp"
android:textStyle="bold"
android:layout_centerInParent="true"/>
</RelativeLayout>
Likewise create few more fragment activities with same code we used for OneFragment.java.
See this simple complete example:
Here I used TabLayout also which is often used with ViewPager, so will be useful for you on next.
It requires API:
compile 'com.android.support:design:25.3.1'
You can ignore and remove all parts of TabLayout from xml and java files if want to go simpler at this instance.
1. activity_main.xml
<?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="match_parent">
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewPager"/>
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
app:tabIndicatorColor="#color/colorPrimaryDark"
app:layout_scrollFlags="scroll|enterAlways"
android:id="#+id/tabLayout"/>
</RelativeLayout>
2. Fragment Tab1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="TAB 1"
android:id="#+id/textTab1"/>
</RelativeLayout>
3. Fragment Tab2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="TAB 2"
android:id="#+id/textTab2"/>
</RelativeLayout>
4. Fragment Tab3.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="TAB 3"
android:id="#+id/textSpacerNoTitleab3"/>
</RelativeLayout>
5. MainActivity.java
public class MainActivity extends AppCompatActivity
implements TabLayout.OnTabSelectedListener, ViewPager.OnPageChangeListener{
ViewPager viewPager;
TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setText("Page 1"));
tabLayout.addTab(tabLayout.newTab().setText("Page 2"));
tabLayout.addTab(tabLayout.newTab().setText("Page 3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.addOnTabSelectedListener(this);
viewPager.setAdapter(new VPAdapter(getSupportFragmentManager()));
viewPager.addOnPageChangeListener(this);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
w("onTabSelected(): "+tab.getPosition());
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
w("onPageSelected(): "+position);
TabLayout.Tab tab = tabLayout.getTabAt(position);
if(tab!=null)tab.select();
}
#Override
public void onPageScrollStateChanged(int state) {
}
void w(String string){
Log.w("MKN",getClass().getSimpleName()+" "+string);
}
}
6. Fragment class Tab1.java
public class Tab1 extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.tab1,container,false);
}
}
7. Fragment class Tab2.java
public class Tab2 extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.tab2,container,false);
}
}
8. Fragment class Tab3.java
public class Tab3 extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.tab3,container,false);
}
}
9. Adapter class VPAdapter.java
public class VPAdapter extends FragmentPagerAdapter {
public VPAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if(position == 0) return new Tab1();
if(position == 1) return new Tab2();
if(position == 2) return new Tab3();
throw new IllegalStateException("Unexpected position " + position);
}
#Override
public int getCount() {
return 3;
}
}
Use this :
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
// adding the fragments here with titles
adapter.addFragment(new OneFragment(), "ONE");
adapter.addFragment(new TwoFragment(), "TWO");
adapter.addFragment(new ThreeFragment(), "THREE");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
//return null;
}
}
then set it like this:
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) view.findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager);
hope it helps!!!

How to hide and show FloatingActionButton with Fragments in a ViewPager?

I am trying to only show my FloatingActionButton on one fragment and hide in the rest. I have tried multiple answers and nothing is working. I tried this solution:
Hide a Floating Action Button of another Layout
But it isn't working. I tried adding buttons on two of the fragments, one that shows and one that hides the FAB and that works, but once I remove the button, it won't show automatically. Here is my code:
hidden_fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
shown_fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
HiddenFragment.java:
public class HiddenFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
View view = inflater.inflate(R.layout.hidden_fragment, container, false);
final FloatingActionButton fab = ((MainActivity) getActivity()).getFloatingActionButton();
if (fab != null) {
((MainActivity) getActivity()).hideFloatingActionButton();
}
return view;
}
}
ShownFragment.java:
public class ShownFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
View view = inflater.inflate(R.layout.hidden_fragment, container, false);
final FloatingActionButton fab = ((MainActivity) getActivity()).getFloatingActionButton();
if (fab != null) {
((MainActivity) getActivity()).showFloatingActionButton();
}
return view;
}
}
In my MainActivity.java I have this:
public FloatingActionButton getFloatingActionButton() {
return fab;
}
public void showFloatingActionButton() {
fab.show();
}
public void hideFloatingActionButton() {
fab.hide();
}
The way I currently have it doesn't work. When I launch the app, the first fragment launched is the HiddenFragment. But when I go to the ShownFragment, the FAB doesn't appear. I tried a different approach, I added a button to each fragment and added the showFloatingActionButton() and hideFloatingActionButton() to the buttons and that works. Does anyone know what I am doing wrong?
For showing/hiding a FloatingActionButton with Fragments in a ViewPager, just use a ViewPager.OnPageChangeListener and show the FloatingActionButton for the positions you want, and hide it for the positions you want.
This would go in the Activity:
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
switch (position) {
case 0:
fab.hide();
break;
case 1:
fab.show();
break;
case 3:
fab.hide();
break;
default:
fab.hide();
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
Hide the floating button from other fragment. It work in my case.
in MainActivity.java add:
private ActivityMainBinding binding;
public FloatingActionButton getFloatingActionButton() {
return binding.fab;
}
onCreateView in SecondFragment:
private FloatingActionButton floatingButton;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
floatingButton = ((MainActivity) getActivity()).getFloatingActionButton();
floatingButton.hide();
...
}

ViewPager and TabLayout in Fragment. setAdapter on a null object reference

I'm trying to add viewPager in Fragment. But when I start my application I receive this:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.view.ViewPager.setAdapter(android.support.v4.view.PagerAdapter)' on a null object reference
My MainFragment:
public class YourTasksFragment extends Fragment {
#Bind(R.id.viewpager)
ViewPager viewPager;
#Bind(R.id.tabs)
TabLayout tabLayout;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_your_tasks, container, false);
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
adapter.addFragment(new OneFragment(), "ONE");
adapter.addFragment(new TwoFragment(), "TWO");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager childFragmentManager) {
super(childFragmentManager);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
}
}
Layout:
<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="match_parent">
<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.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" />
You forgot to setup Butterknife in the onCreateView(), therefore the variable is never initialized.
Do this:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_your_tasks, container, false);
Butterknife.bind(this,v);
return v;
}
Hope it helps!
You forgot to add Butterknife.bind(this, v) on the method onCreateView.
It's required in order to bind the views.
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_your_tasks, container, false);
Butterknife.bind(this,v);
return v;
}

Simple fragmented tabhost in android

I am trying to implement fragment-Tabhost in android
MainActivity.java
public class MainActivity extends Activity {
// Declare Tab Variable
ActionBar.Tab Tab1, Tab2;
Fragment fragmentTab2 = new FragmentTab2();
//Fragment fragmentTab3 = new FragmentTab3();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getActionBar();
// Hide Actionbar Icon
actionBar.setDisplayShowHomeEnabled(false);
// Hide Actionbar Title
actionBar.setDisplayShowTitleEnabled(false);
// Create Actionbar Tabs
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set Tab Icon and Titles
Tab1 = actionBar.newTab().setText("Tab1");
//Tab2 = actionBar.newTab().setText("Tab2");
// Set Tab Listeners
Tab1.setTabListener(new TabListener(fragmentTab2));
//Tab2.setTabListener(new TabListener(fragmentTab3));
// Add tabs to actionbar
actionBar.addTab(Tab1);
//actionBar.addTab(Tab2);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
FragmentTab2.java
public class FragmentTab2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmenttab2, container, false);
return rootView;
}
}
FragmentTab3.java
public class FragmentTab3 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmenttab3, container, false);
return rootView;
}
}
At present just one tab with one activity is displaying
What i am trying to do ::
click on tab1(first time) - - - - > FragmentTab2.java must display
Click on tab1(second time) - - - - > FragmentTab3.java must display
click on tab1(third time)- - - - > FragmentTab2.java must display again
This cycle must keep on repeating itself
What code changes should i need to make ?
Any IDEAS ?
I got it to work, you still need to make some adjustments, but it will get you started.
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity implements Notify, TabListener {
ActionBar.Tab tab1;
ActionBar actionBar;
int count = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFragmentManager().beginTransaction().replace(R.id.container, new FragmentTab2()).commit();
actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
tab1 = actionBar.newTab().setText("Tab1");
tab1.setTabListener(this);
actionBar.addTab(tab1);
}
//Callback
#Override
public void notifyTabListener() {
count++;
Tab tab = actionBar.newTab().setText("Tab" + count);
tab.setTabListener(this);
actionBar.addTab(tab);
}
//Tablistener
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
ft.replace(R.id.container, new FragmentTab2());
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.add(new FragmentTab2(), "Tab" + count);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
Notify callback:
public interface Notify {
public void notifyTabListener();
}
FragmentTab2:
public class FragmentTab2 extends Fragment implements OnClickListener {
Notify mCallback;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.f2, container, false);
LinearLayout layout = (LinearLayout) rootView.findViewById(R.id.layout2);
layout.setOnClickListener(this);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallback = (MainActivity) activity;
}
#Override
public void onClick(View v) {
mCallback.notifyTabListener();
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
f2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView android:text="Fragment2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
You need to implement TabListener and set to Tab1.setTabListener().
When onTabSelected(), repeating replace fragment1 or fragment2.

Categories