RecyclerView: No adapter attached; skipping layout - What is missing in the main? - java

Before put -1 in the score, I tell you that I read all, I repeat ALL the answers about this problem in this site and even in other site, so, if you can give me an hand.
Hi guys, i'm having this problem with my application and I'm wasting too much time in this.
My application is composed by 4 fragments, and I'm having problems with the two with the recyclerview (in fragment_fibra and fragment_adsl).
main.java
public class main extends AppCompatActivity implements
OnFragmentInteractionListener //I HAVE a problem with
OnFragmentInteractionListener {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = findViewById(R.id.tabs);
// tabLayout.setupWithViewPager(mViewPager); //aggiunta dopo
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
#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_homepage, 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 class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
switch(getArguments().getInt(ARG_SECTION_NUMBER))
{
case 1:
rootView = inflater.inflate(R.layout.fragment_homepage, container, false);
break;
case 2:
rootView = inflater.inflate(R.layout.fragment_fibra, container, false);
break;
case 3:
rootView = inflater.inflate(R.layout.fragment_adsl, container, false);
break;
case 4:
rootView = inflater.inflate(R.layout.fragment_aiuto, container, false);
break;
}
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return PlaceholderFragment.newInstance(1);
case 1:
return PlaceholderFragment.newInstance(2);
case 2:
return PlaceholderFragment.newInstance(3);
case 3:
return PlaceholderFragment.newInstance(4);
default: return PlaceholderFragment.newInstance(1);
// here i have other problems, so like this the app still work, but if i change something it crash (and I know it's wrong like this)
}
//return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 4;
}
}
}
activity_homepage.xml
<?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:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".homepage">
<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.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_weight="1"
android:background="#color/colorPrimaryDark"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/PopupOverlay"
app:title="#string/app_name">
</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:background="#color/colorPrimary">
<android.support.design.widget.TabItem
android:id="#+id/tabItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_1" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_2" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_3" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_4" />
</android.support.design.widget.TabLayout>
</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.support.design.widget.CoordinatorLayout>
homepage.java (first fragment)
public class homepage extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_homepage, 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 class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
switch(getArguments().getInt(ARG_SECTION_NUMBER))
{
case 1:
rootView = inflater.inflate(R.layout.fragment_homepage, container, false);
break;
case 2:
rootView = inflater.inflate(R.layout.fragment_fibra, container, false);
break;
case 3:
rootView = inflater.inflate(R.layout.fragment_adsl, container, false);
break;
case 4:
rootView = inflater.inflate(R.layout.fragment_aiuto, container, false);
break;
}
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 4;
}
}
}
fragment_fibra.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fibra"
android:background="#EFEFEF">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:drawablePadding="22dp"
android:gravity="center"
android:hint="#string/cercasugg"
android:textColor="#000000"
android:padding="16dp" />
<android.support.v7.widget.RecyclerView
android:id="#+id/ListaFibra"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
fibra.java (second fragment)
public class fibra extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private OnFragmentInteractionListener mListener;
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
public fibra() {
}
public static fibra newInstance(String param1, String param2) {
fibra fragment = new fibra();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.fragment_fibra, container, false);
recyclerView = V.findViewById(R.id.ListaFibra);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
List<String> input = new ArrayList<>();
for (int i = 0; i < 100; i++) {
input.add("Test" + i);
}
mAdapter = new adFibra(input);
recyclerView.setAdapter(mAdapter);
return V;
/*View rootView = inflater.inflate(R.layout.fragment_fibra, container, false);
RecyclerView recyclerView = rootView.findViewById(R.id.ListaFibra);
recyclerView.setHasFixedSize(true); //per migliorare performance
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(llm);
adFibra adapter = new adFibra(new String[]{"Example One"});
recyclerView.setAdapter(adapter);
return rootView;*/
//return inflater.inflate(R.layout.fragment_fibra, container, false);
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}

try to put
recyclerView.setLayoutManager(llm);
before
recyclerView.setAdapter(adapter);
so it will be
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(llm);
MyAdapter adapter = new MyAdapter(new String[]{"Example One", "Example Two", "Example Three", "Example Four", "Example Five" , "Example Six" , "Example Seven"});
recyclerView.setAdapter(adapter);
Happy Coding :D

Are you sure you actually call the fibra fragment?
You are creating a PlaceHolderFragment every time and just inflating different layouts. You don't actually create a fibra fragment, so the recycler is not populated, thus the message.
In your SectionsPagerAdapter, in method getItem, return the fragment instance that corresponds to the position.
For example:
switch (position) {
case 0:
return homepage.newInstance();
case 1:
return fibra.newInstance();
case 2:
return adsl.newInstance();
case 3:
return aiuto.newInstance();
default:
return homepage.newInstance();
}
Remove the PlaceHolderFragment from your main activity. Also homepage is not a fragment, but an activity. All your fragments should look like fibra.
And implement all the fragment interfaces like:
implements fibra.OnFragmentInteractionListener
and create a method to implement it:
#Override
public void onFragmentInteraction(Uri uri) {
// your code here...
}

Related

Run new fragment instance with viewpager on click on menu item

I have a working fragment code based on Android Studio's "Tabbed Activity" project structure. However, since I have dynamically created content filling the space, the standard swipe isn't applicable and I'd like to toggle between fragments when selecting an item from a menu.
This is my code for the fragments:
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber)
{
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup containerPager,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, containerPager, false);
TextView textView = (TextView) rootView.findViewById(R.id.temporary);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
// FRAGMENT 1 - First. This one should have a blank layout!
public static class FragmentFirst extends Fragment {
public static FragmentFirst newInstance(int sectionNumber) {
FragmentFirst fragment = new FragmentFirst();
return fragment;
}
public FragmentFirst() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup containerPager,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_first, containerPager, false);
return rootView;
}
}
// FRAGMENT 2 - Second
public static class FragmentSecond extends Fragment {
public static FragmentSecond newInstance(int sectionNumber) {
FragmentSecond fragment = new FragmentSecond();
return fragment;
}
public FragmentSecond() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup containerPager,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, containerPager, false);
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position) {
case 0:
return FragmentFirst.newInstance(position + 1);
case 1:
return FragmentSecond.newInstance(position + 1);
default:
//assume you only have 2
throw new IllegalArgumentException();
}
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
}
OnCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
ViewPager mViewPager = (ViewPager) findViewById(R.id.containerPager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
Furthermore, here is the code for choosing the particular menu item:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.change_fragment)
{
// Can I run/initiate the code at public Fragment getItem(int position) {}
// from here?
// The lines below do work, but rather than running the fragments' code,
// it simply overlaps with the current content.
ViewPager mViewPager = (ViewPager) findViewById(R.id.containerPager);
mViewPager.setCurrentItem(1, true);
return true;
}
return super.onOptionsItemSelected(item);
}
I am familiar with mViewPager.setCurrentItem(position, true), however, rather than applying the fragment over the current layout, I'd like to trigger the fragment code so it can change between layouts - in this case, to fragment_main, or FragmentSecond.
Problem:
Is it possible to run the code in public Fragment getItem(int position) {} outside its class SectionsPagerAdapter extends FragmentPagerAdapter? Or is there a better way to achieve what I'm looking for?
public Fragment getItem(int position) {
switch(position)
{
case 0:
FragmentMain tab1 = new FragmentMain ();
return tab1;
case 1:
FragmentSecond tab2 = new FragmentSecond ();
return tab2;
default:
return null;
}
i use this to switch fragments
XML :
<?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">
<RelativeLayout
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:layout_alignParentStart="true"
android:background="#color/colorPrimary"
app:tabGravity="fill"
app:tabIndicatorColor="#color/black"
app:tabMode="fixed"
app:tabSelectedTextColor="#color/black"
app:tabTextAppearance="#style/buttonThemePrimaryHolo1"
app:tabTextColor="#fff" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/tabs">
</android.support.v4.view.ViewPager>
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
In Activity :
TabLayout tabLayout;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate ( savedInstanceState );
setContentView ( R.layout.activity_main );
viewPager = findViewById ( R.id.viewpager );
setupViewPager ( viewPager );
tabLayout = findViewById ( R.id.tabs );
tabLayout.setupWithViewPager ( viewPager );
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter ( getSupportFragmentManager () );
adapter.addFragment ( new Fragment1 (), "Fragment1 " );
adapter.addFragment ( new Fragment2 (), "Fragment2 " );
adapter.addFragment ( new Fragment3 (), "Fragment3 " );
adapter.addFragment ( new Fragment4 (), "Fragment4 " );
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 );
}
}
In Fragment
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter ( getChildFragmentManager() );
adapter.addFragment ( new Fragment1 (), "Fragment1 " );
adapter.addFragment ( new Fragment2 (), "Fragment2 " );
adapter.addFragment ( new Fragment3 (), "Fragment3 " );
adapter.addFragment ( new Fragment4 (), "Fragment4 " );
viewPager.setAdapter ( adapter );
}
Other part are same as activity in fragment

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 create a Tabbed Activity with ListViews - Android

First of all, I'm a beginner in Android programming. What I'm trying to do is to program three Tabs with each a ListView inside (you know it from e.g. WhatsApp). Android Studio makes it easy to automatically create a Tabbed Activity. So the question is: how can I implement a ListView for each Tab?
Actually there is a nice tutorial on http://www.androidhive.info/2012/05/android-combining-tab-layout-and-list-view/ which uses TabActivity. However this method is deprecated and Fragments should be used instead. I have extended main_fragment.xml (which was created by Android Studio) with a ListView. But what is the correct way to set the corresponding list adapters and especially where to set them? Setting them like ListView list_all = (ListView) findViewById(R.id.listViewAll) in onCreate() does not work because of a null object reference error. Also I didn't find out how to use the rootView which is returned by onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) So how can I solve this problem?
main_fragment.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:background="#color/colorAccent"
android:paddingTop="#dimen/activity_vertical_margin">
<ListView
android:id="#+id/listViewAll"
android:layout_width="match_parent"
android:layout_height="match_parent"></ListView>
</RelativeLayout>
main.xml:
<?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:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:background="#color/white"
tools:context="de.url.members">
<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:background="#color/bg_login_dark"
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="#color/bg_login_dark"
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"
app:tabMaxWidth="0dp"
app:tabGravity="fill"
app:tabMode="fixed"
android:fillViewport="false" />
</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.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
main.java:
public class main extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
// The {#link ViewPager} that will host the section contents.
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// action here
}
});
}
#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_members, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.logout) {
//action here
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
int sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);//INDEX of selected TAB
View rootView;
if (sectionNumber == 1){
rootView = inflater.inflate(R.layout.main_fragment, container, false);
}else if (sectionNumber == 2){
rootView = inflater.inflate(R.layout.main_fragment, container, false);
}else if (sectionNumber == 3){
rootView = inflater.inflate(R.layout.main_fragment, container, false);
}else{
rootView = inflater.inflate(R.layout.main_fragment, container, false);
}
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getResources().getString(R.string.title_section1);
case 1:
return getResources().getString(R.string.title_section2);
case 2:
return getResources().getString(R.string.title_section3);
}
return null;
}
}
}
If you want to use Listing with tablayout and viewpager try this way it will work for you
public class MainActivity extends AppCompatActivity {
private static Toolbar toolbar;
private static ViewPager viewPager;
private static TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewPager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);//setting tab over viewpager
//Implementing tab selected listener over tablayout
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());//setting current selected item over viewpager
switch (tab.getPosition()) {
case 0:
Log.e("TAG","TAB1");
break;
case 1:
Log.e("TAG","TAB2");
break;
case 2:
Log.e("TAG","TAB3");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
//Setting View Pager
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new DummyFragment("ANDROID"), "ANDROID");
adapter.addFrag(new DummyFragment("iOS"), "iOS");
adapter.addFrag(new DummyFragment("WINDOWS"), "WINDOWS");
viewPager.setAdapter(adapter);
}
//View Pager fragments setting adapter class
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();//fragment arraylist
private final List<String> mFragmentTitleList = new ArrayList<>();//title arraylist
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
//adding fragments and title method
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
For more see android-material-design-tabs-using-tablayout
OR
Check this http://www.tutorialsbuzz.com/2015/10/Android-Sliding-TabLayout-ListView-WhatsApp.html
And check this https://github.com/codepath/android_guides/wiki/Handling-Scrolls-with-CoordinatorLayout
OUTPUT
I will explain what you have to do to put a ListView on one of the fragments. (Sorry if I write a bad English)
You should put your listView view on the xml witch is displayed by one of your fragments. In the code that you have post the layout witch fragment displays is R.layout.main_fragment
Then on the fragment you have to declare your ListView:
ListView list_all = (ListView) rootView.findViewById(R.id.listViewAll);
You have to create a ListView adapter, an object class and some other files, you can use the tutorial witch you have post.
Link
Then write your code to set an Adapter to this ListView after the rootView is assigned on the fragment:
if (sectionNumber == 1){
rootView = inflater.inflate(R.layout.main_fragment, container, false);
}else if (sectionNumber == 2){
rootView = inflater.inflate(R.layout.main_fragment, container, false);
}else if (sectionNumber == 3){
rootView = inflater.inflate(R.layout.main_fragment, container, false);
}else{
rootView = inflater.inflate(R.layout.main_fragment, container, false);
}
ArrayList<Object> arrayListOfObjects = new ArrayList<>();
arrayListOfObjects.add(new Object(...));
MyAdapter adapter = new MyAdapter(arrayListOfObjects);
list_all.setListAdapter(adapter);
I have solved it now by simply editing the getItem() method of public class SectionsPagerAdapter in main.java.
Just return a default ListFragment instead of the PlaceholderFragment.
Interesting note: Returning the same ListFragment object for all tabs leads to an error.
main.java:
public class MainActivity extends AppCompatActivity {
private ArrayAdapter<String> adapter;
private ListFragment contacts1 = new ListFragment();
private ListFragment contacts2 = new ListFragment();
private ListFragment contacts3 = new ListFragment();
List<String> words = new ArrayList<String>();
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
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);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
words.add("Hello");
words.add("World");
words.add("!");
adapter = new ArrayAdapter<String>(this,R.layout.item,words);
contacts1.setListAdapter(adapter);
contacts2.setListAdapter(adapter);
contacts3.setListAdapter(adapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Update List", Snackbar.LENGTH_LONG).setAction("Action", null).show();
words.add("New Item");
adapter.notifyDataSetInvalidated();
}
});
}
#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_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
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 ListFragment getItem(int position) {
if (position == 0){
return contacts1;
}else if (position == 1){
return contacts2;
}else{
return contacts3;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
}
}

How do I use android fragment java class?

I set up a fragment which looks like this:
The EditText("5") has the id et_input. Now I want to interact with my EditText but it doesn't work.
MainActivity.java
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
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);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
getSupportActionBar().hide();
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
switch (getArguments().getInt(ARG_SECTION_NUMBER) - 1) {
case 1:
return inflater.inflate(R.layout.fragment_roman_numbers, container, false);
case 2:
return inflater.inflate(R.layout.fragment_binary_numbers, container, false);
default:
return inflater.inflate(R.layout.fragment_main, container, false);
}
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if(position == 0) {
return main.newInstance();
} else if(position == 1) {
return roman_numbers.newInstance();
} else if(position == 2) {
return binary_numbers.newInstance();
}
throw new IllegalArgumentException("There is no fragment for position [" + position + "]");
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.fragment_home);
case 1:
return getString(R.string.fragment_roman_numbers);
case 2:
return getString(R.string.fragment_binary_numbers);
}
return null;
}
}
}
binary_numbers.java
public class binary_numbers extends Fragment {
public binary_numbers() {
// Required empty public constructor
}
public static binary_numbers newInstance() {
binary_numbers fragment = new binary_numbers();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_binary_numbers, container, false);
EditText et_input = (EditText) view.findViewById(R.id.et_input);
et_input.setText("TEST");
// Inflate the layout for this fragment
return view;
}
}
roman_numbers.java and main.java look exactly the same except for binary_numbers being replaced with their names.
fragement_binary_numbers.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.ngtnttnmnt.xtool.MainActivity$PlaceholderFragment">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/et_input"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:hint="#string/input_hint"
android:gravity="center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:id="#+id/tv_output"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textSize="40dp"
android:gravity="center" />
fragement_roman_numbers.xml looks exactly the same and fragement_main.xml has two TextView's
Should be
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_binary_numbers, container, false);
EditText et_input = (EditText) view.findViewById(R.id.et_input);
et_input.setText("TEST");
// Inflate the layout for this fragment
return view;
}
EDIT:
As I said, you're showing a different fragment. In reality, you are showing the PlaceholderFragment created within your SectionsPagerAdapter, which just selects the binary_number layout when it's inflated, but you're not actually showing a binary_numbers fragment.
Your code should be the following:
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());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
getSupportActionBar().hide();
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if(position == 0) {
return home.newInstance();
} else if(position == 1) {
return roman_numbers.newInstance();
} else if(position == 2) {
return binary_numbers.newInstance();
}
throw new IllegalArgumentException("There is no fragment for position [" + position + "]");
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.fragment_home);
case 1:
return getString(R.string.fragment_roman_numbers);
case 2:
return getString(R.string.fragment_binary_numbers);
}
throw new IllegalArgumentException("There is no fragment for position [" + position + "]");
}
}
}
Please note the complete removal of the PlaceholderFragment class, because you won't need it, ever.
EDIT: also add
public class home extends Fragment {
public static home newInstance() {
return new home();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
}
EDIT:
Also modify your binary_numbers class like so
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import com.ngtnttnmnt.xtool.InputFilterMinMax;
import com.ngtnttnmnt.xtool.R;
public class binary_numbers extends Fragment {
public binary_numbers() {
// Required empty public constructor
}
public static binary_numbers newInstance() {
binary_numbers fragment = new binary_numbers();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_binary_numbers, container, false);
EditText et_input = (EditText) view.findViewById(R.id.et_input);
et_input.setText("TEST");
// Inflate the layout for this fragment
return view;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private PlaceholderFragment mPlaceholderFragment;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if(mPlaceholderFragment == null){
mPlaceholderFragment = PlaceholderFragment.newInstance(position + 1);
}
return mPlaceholderFragment;
}
It should be like this

Android ViewPager child fragments load but tabs don't

I'm using a ViewPager in a fragment that loads a child fragment per tab, and that is working fine the child fragments are loaded, but the issue is that the tabs themselves, where the tab click-able names go, is not showing, nor is it responding to click events. I reach this screen by selecting an element in a recyclerview in a previous fragment.
The expected layout structure is the following:
But the problem is that, although everything else loads fine and I can side swipe to switch child fragments, the tab bar doesn't load at all and I just get this:
I'm not sure what is causing this, but when I rotate the screen and back, then they appear.
MainActivity class
public class MainActivity extends AppCompatActivity {
private final static int PROFILE_FRAGMENT = 1;
private final static int PRIZES_FRAGMENT = 2;
private final static int STORES_FRAGMENT = 3;
private final static int ABOUT = 4;
private int currentFragment = 3;
private String currentFragmentName = "StoresListFragment";
public int HEADER_IMAGE = R.drawable.avatar;
private DrawerLayout drawer;
private List<DrawerItem> dataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
FragmentManager fm = getSupportFragmentManager();
if (getIntent().getStringExtra("STORE_DETAILS") != null) {
openFragment(new StoreDetailsFragment());
setTitle(getString(R.string.title_store_details));
}
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
}
RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView);
mRecyclerView.setHasFixedSize(true);
dataList = new ArrayList<>();
addItemsToDataList();
NavDrawerAdapter mAdapter = new NavDrawerAdapter(dataList, this, db.getClientName(), db.getPoints(), HEADER_IMAGE);
mRecyclerView.setAdapter(mAdapter);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
drawer = (DrawerLayout) findViewById(R.id.DrawerLayout);
drawer.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
this, drawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
drawer.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
onTouchDrawer(currentFragment);
final GestureDetector mGestureDetector =
new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
View child = recyclerView.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if (child != null && mGestureDetector.onTouchEvent(motionEvent)) {
drawer.closeDrawers();
onTouchDrawer(recyclerView.getChildLayoutPosition(child));
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
private void addItemsToDataList() {
dataList.add(new DrawerItem(getString(R.string.title_profile), R.mipmap.ic_action_profile));
dataList.add(new DrawerItem(getString(R.string.title_prizes), R.mipmap.ic_action_prizes));
dataList.add(new DrawerItem(getString(R.string.title_stores), R.mipmap.ic_action_sales));
dataList.add(new DrawerItem(getString(R.string.title_about), R.mipmap.ic_action_about));
}
public void openFragment(final Fragment fragment) {
if (!fragment.toString().equalsIgnoreCase(currentFragmentName)) {
// update the transfer content by replacing fragments
currentFragmentName = fragment.toString();
switchContent(fragment);
}
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commitAllowingStateLoss();
}
private void onTouchDrawer(final int position) {
currentFragment = position;
switch (position) {
case PROFILE_FRAGMENT:
openFragment(new ProfileFragment());
setTitle(getString(R.string.title_profile));
break;
case PRIZES_FRAGMENT:
openFragment(new PrizesListFragment());
setTitle(getString(R.string.title_prizes));
break;
case STORES_FRAGMENT:
openFragment(new StoresListFragment());
setTitle(getString(R.string.title_stores));
break;
case ABOUT:
openFragment(new AboutFragment());
setTitle(getString(R.string.title_about));
break;
default:
}
}
/*
* helper to switch content with backstack
*/
public void switchContent(Fragment fragment) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragment)
// add to backstack
.addToBackStack(fragment.getClass().getSimpleName())
.commitAllowingStateLoss();
}
#Override
protected void onResume() {
if (getIntent().getStringExtra("SALES_LIST") != null) {
openFragment(new StoreDetailsFragment());
setTitle(getString(R.string.title_store_details));
} else if (getSupportFragmentManager().getBackStackEntryCount() <= 0) {
openFragment(new StoresListFragment());
setTitle(getString(R.string.title_stores));
}
super.onResume();
}
}
The fragment in question:
public class StoreDetailsFragment extends Fragment {
private ViewPager viewPager;
private Store storeSelected = null;
private TextView storeName;
private ImageView bannerImage;
private TextView storesubtitle;
public StoreDetailsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_store_details, container, false);
viewPager = (ViewPager) rootView.findViewById(R.id.tabanim_viewpager);
TabLayout storeTabLayout = (TabLayout) rootView.findViewById(R.id.tabanim_tabs);
setupViewPager(viewPager);
storeTabLayout.setupWithViewPager(viewPager);
storeTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
switch (tab.getPosition()) {
case 0:
Toast.makeText(getActivity(), "Sales List", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(getActivity(), "Store Description", Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(getActivity(), "Store Ratings", Toast.LENGTH_SHORT).show();
break;
case 3:
Toast.makeText(getActivity(), "Images", Toast.LENGTH_SHORT).show();
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
bannerImage = (ImageView) rootView.findViewById(R.id.store_details_banner_image);
storeName = (TextView) rootView.findViewById(R.id.text_store_details_name);
storesubtitle = (TextView) rootView.findViewById(R.id.text_store_details_subtitle);
return rootView;
}
#Override
public void onResume() {
super.onResume();
// Set title
getMainActivity().setTitle(R.string.title_store_details);
}
protected MainActivity getMainActivity() {
return (MainActivity) getActivity();
}
}
Fragment in question's layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
android:id="#+id/main_content"
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="300dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:id="#+id/store_details_banner_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="?attr/actionBarSize"
android:background="#drawable/white_placeholder"
android:contentDescription=""
android:fitsSystemWindows="true"/>
<LinearLayout
android:id="#+id/smth"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginBottom="?attr/actionBarSize"
android:background="#ffffff"
android:orientation="vertical">
<TextView
android:id="#+id/text_store_details_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="18dp"
android:layout_marginTop="40dp"
android:textColor="#333"
android:textSize="15sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/text_store_details_subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginStart="13dp"
android:layout_marginTop="3dp"
android:drawableLeft="#mipmap/ic_action_store_house"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#333"/>
</LinearLayout>
<android.support.v7.widget.Toolbar
android:id="#+id/anim_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/transparent"
app:layout_collapseMode="parallax"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.TabLayout
android:id="#+id/tabanim_tabs"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="bottom"
android:visibility="visible"
app:tabGravity="center"
app:tabIndicatorColor="#F1514A"
app:tabMode="scrollable"
app:tabSelectedTextColor="#android:color/white"
app:tabTextColor="#99ffffff"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/tabanim_viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
</android.support.design.widget.CoordinatorLayout>
And the ViewPagerAdaper:
public class StoreDetailsViewPagerTabAdaper extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public StoreDetailsViewPagerTabAdaper(FragmentManager manager) {
super(manager);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(android.support.v4.app.Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}}
Any help and suggestions are appreciated.
In the end I couldn't find a solution to this and even after consulting some more experienced developers we could only find a workaround, which was just have this be inside an activity instead of a fragment and then the viewpager behaves as expected. I couldn't figure out why it doesn't inside a fragment.
If anyone finds a more suitable answer, go ahead, but until then I'll set this to be the accepted answer.
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
Try this one and initiate your adapter with getChildFragmentManager
I would try to log inside getPageTitle, because I think when you rotate the screen everything is destroyed an the mFragmentTitleList is empty when you redraw the titles, so try to find out what's going on by doing something like:
#Override
public CharSequence getPageTitle(int position) {
Log.d("ViewPagerAdapter", "Displaying title: "+ mFragmentTitleList.get(position));
return mFragmentTitleList.get(position);
}
Your TabLayout might not be showing because you set height to it. Try setting android:layout_height="wrap_content".
You don't have to handle tab clicks manually – if you bind the TabLayout with ViewPager
tabLayout.setupWithViewPager(viewPager);
the listener is created automatically. I would suggest to remove the custom listener.

Categories