ViewPager not displaying fragments - android

I'm making an app and the Main Activity has a tablayout connected to a viewpager. This viewpager has three fragments.
I know that the viewpager adapter manages 3 fragments (the correct amount) because I used Logging statements. Also, I use asyncTasks to load data into the fragments and it is done correctly. When the data is loaded, it populates a recyclerview. I used logging statements and I know that each fragment has a recyclerview with 20 entries, which is correct.
But for some reason, my viewpager does not display the fragments, even though when I call getItemCount() on it, I get the right number of fragments.
Can you help me to figure out why the fragments are being created but not displayed?
Thank you.
This is my MainActivity:
public class MovieListActivity extends AppCompatActivity {
public static final String POPULAR = "popular";
public static final String TOP = "top";
public static final String FAVORITES = "favorites";
private static final String QUERY_TYPE = "query type";
private RecyclerView mRecyclerView;
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
private boolean mTwoPane;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
setupTabLayout();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
if (findViewById(R.id.movie_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
}
}
private void setupTabLayout() {
TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
tabLayout.addTab(tabLayout.newTab().setText(POPULAR));
tabLayout.addTab(tabLayout.newTab().setText(TOP));
tabLayout.addTab(tabLayout.newTab().setText(FAVORITES));
List<Fragment> fragments = new ArrayList<>();
for (int i=0;i<3;i++) {
Bundle bundle = new Bundle();
bundle.putInt(QUERY_TYPE, i);
fragments.add(ListFragment
.instantiate(this,ListFragment.class.getName(),bundle));
}
viewPager.setAdapter(new MoviePagerAdapter(getSupportFragmentManager(), fragments));
tabLayout.setupWithViewPager(viewPager);
}
}
This is the fragment that the viewpager should instantiate 3 times:
public class ListFragment extends Fragment {
private static final String QUERY_TYPE = "query type";
public static final int POPULAR = 0;
public static final int HIGHEST_RATED = 1;
public static final int FAVORITES = 2;
private RecyclerView mRecyclerView;
private int mListType;
public ListFragment() {}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
mListType = this.getArguments().getInt(QUERY_TYPE);
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.movie_list,container,false);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.movie_list);
assert mRecyclerView != null;
setupRecyclerView(mRecyclerView);
if (mListType == HIGHEST_RATED || mListType == POPULAR) {
requestMovies();
}
return super.onCreateView(inflater, container, savedInstanceState);
}
private void setupRecyclerView(#NonNull RecyclerView recyclerView) {
recyclerView.setAdapter(new MovieAdapter(getActivity()));
}
void setMovies(Movie[] movies) {
MovieAdapter movieAdapter = (MovieAdapter)mRecyclerView.getAdapter();
movieAdapter.setMovies(movies);
movieAdapter.notifyDataSetChanged();
}
private void requestMovies() {
if (mRecyclerView.getAdapter().getItemCount() == 0) {
new FetchMoviesTask(this).execute(POPULAR);
}
}
}
Pager Adapter:
public class MoviePagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> mFragments;
public MoviePagerAdapter(FragmentManager fm, List<Fragment> mFragments) {
super(fm);
this.mFragments = mFragments;
}
#Override
public Fragment getItem(int position) {
return this.mFragments.get(position);
}
#Override
public int getCount() {
return mFragments==null? 0 : mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case ListFragment.POPULAR:
return MovieListActivity.POPULAR;
case ListFragment.HIGHEST_RATED:
return MovieListActivity.TOP;
case ListFragment.FAVORITES:
return MovieListActivity.FAVORITES;
default:
throw new IllegalArgumentException("Requesting a fragment that doesn't exist");
}
}
}
Just in case: these are the xml files for the activity and fragment:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MovieListActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="#style/AppTheme.PopupOverlay" />
<android.support.design.widget.TabLayout
android:id="#+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
</android.support.v4.view.ViewPager>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/movie_list"
android:name="com.example.madelenko.app.moviegami.MovieListFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layoutManager="GridLayoutManager"
app:spanCount="2"
tools:context="com.example.madelenko.app.moviegami.MovieListActivity"
tools:listitem="#layout/movie_list_content" />

return your view which you inflate in Fragment,
#Nullable
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.movie_list,container,false);
return rootView ;
}

Related

ViewPager inside Fragment doest show content

im developing an android app which has a bottomnavigation that opens 3 different fragments without a viewpager. One fragment has a viewpager inside it which opens 2 fragments. these 2 fragments are the same fragment and each has a recyclerview inside it. my problem is that when I run the app everything except the viewpager runs as intended. I tried putting the fragment inside the viewpager instead of it and the fragment works. I even tried putting the viewpager in a empty activity which worked as well.
This is my MainActivity which holds the BottomNavigation and its functionality:
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
private androidx.appcompat.widget.Toolbar toolbar;
private BottomNavigationView navView;
private Fragment fragment1 = new HomeFragment();
private Fragment fragment2 = new SearchFragment();
private Fragment fragment3 = new SettingsFragment();
private FragmentManager fm = getSupportFragmentManager();
private Fragment active = fragment1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.action_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Home");
fm.beginTransaction().add(R.id.main_container, fragment3, "settings").hide(fragment3).commit();
fm.beginTransaction().add(R.id.main_container, fragment2, "search").hide(fragment2).commit();
fm.beginTransaction().add(R.id.main_container, fragment1, "home").commit();
navView = findViewById(R.id.nav_view);
navView.setOnNavigationItemSelectedListener(this);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.navigation_home:
fm.beginTransaction().hide(active).show(fragment1).addToBackStack("home").commit();
active = fragment1;
toolbar.setTitle("Home");
return true;
case R.id.navigation_search:
fm.beginTransaction().hide(active).show(fragment2).addToBackStack("search").commit();
active = fragment2;
toolbar.setTitle("Search");
return true;
case R.id.navigation_settings:
fm.beginTransaction().hide(active)
.show(fragment3).addToBackStack("settings").commit();
active = fragment3;
toolbar.setTitle("Settings");
return true;
}
return false;
}
public void setCurrentPage(Fragment fragment, int position) {
if(fm.findFragmentByTag("playlist"+position) != null){
fm.beginTransaction().remove(fragment).hide(active).add(R.id.main_container, fragment, "playlist"+position).addToBackStack(null).commit();
active = fragment;
} else {
fm.beginTransaction().hide(active).add(R.id.main_container, fragment, "playlist"+position).addToBackStack(null).commit();
active = fragment;
}
}
}
This is the MainActivityLayout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
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"
tools:context=".MainActivity">
<include
layout="#layout/action_bar"
android:id="#+id/action_bar"/>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="56dp"
android:layout_marginBottom="70dp"
android:id="#+id/main_container_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:id="#+id/main_container"/>
</androidx.core.widget.NestedScrollView>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/nav_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
android:layout_alignParentBottom="true"
app:menu="#menu/bottom_nav_menu"
app:itemTextColor="#color/bottom_nav_color"
app:itemIconTint="#color/bottom_nav_color"
android:elevation="20dp"/>
</RelativeLayout>
This is my Fragment that implements the ViewPager:
public class HomeFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
PlaylistsPagerAdapter playlistsPagerAdapter = new PlaylistsPagerAdapter(getChildFragmentManager());
playlistsPagerAdapter.addFragment(new PlaylistsFragment(),"private");
playlistsPagerAdapter.addFragment(new PlaylistsFragment(),"public");
ViewPager viewPager = view.findViewById(R.id.pager_home);
viewPager.setAdapter(playlistsPagerAdapter);
TabLayout tabLayout = view.findViewById(R.id.tab_layout_home);
tabLayout.setupWithViewPager(viewPager);
setHasOptionsMenu(false);
}
public class PlaylistsPagerAdapter extends FragmentStatePagerAdapter {
ArrayList<Fragment> mFragmentList = new ArrayList<>();
ArrayList<String> mFragmentListTitle = new ArrayList<>();
public void addFragment(Fragment playlistsFragment, String title) {
mFragmentListTitle.add(title);
mFragmentList.add(playlistsFragment);
}
public PlaylistsPagerAdapter(FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int i) {
return mFragmentList.get(i);
}
#Override
public int getCount() {
return mFragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentListTitle.get(position);
}
}
}
This is the HomeFragmentLayout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.viewpager.widget.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager_home"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tab_layout_home"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</androidx.viewpager.widget.ViewPager>
This is the PlaylistsFragment:
public class PlaylistsFragment extends Fragment {
private static final String TAG = "PlaylistsFragment";
private ArrayList<String> mPlaylistName = new ArrayList<>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_playlists, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initNameBitmap(view);
}
private void initNameBitmap(View view){
mPlaylistName.add("Playlist1");
mPlaylistName.add("Playlist2");
mPlaylistName.add("Playlist3");
mPlaylistName.add("Playlist4");
initRecyclerView(view);
}
private void initRecyclerView(View view){
RecyclerView recyclerView = view.findViewById(R.id.recycler_view_playlists);
RecyclerViewAdapterPlaylists recyclerViewAdapterPlaylists = new RecyclerViewAdapterPlaylists(mPlaylistName, view.getContext(),this);
recyclerView.setAdapter(recyclerViewAdapterPlaylists);
recyclerView.setLayoutManager(new LinearLayoutManager(getView().getContext()));
}
}
This is the PlaylistsFragments Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recycler_view_playlists"
android:layout_margin="10dp" />
</LinearLayout>
The weird thing is that it worked already. I tried around with onBackPressed and when i implemented this and pressed another View on the BottomNavigation than the back button on the phone and than the Home button it showed as intened:
fm.beginTransaction().hide(active).show(fragmentsHistory.get(fragmentsHistory.size()-1));
active = fragmentsHistory.get(fragmentsHistory.size()-1)
fragmentsHistory.remove(fragmentsHistory.size()-1);
What am I doing wrong?
Appreciate the help!
i think the problem is in your layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
tools:context=".ui.plans.PlansFragment">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimaryDark"
app:tabSelectedTextColor="#color/white"
app:tabTextColor="#DBD8D8" />
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
your HomeFragmentLayout should be similar to this

How to add dynamic fragment tab items

I want to add dynamic tab items. I have a fragment which is FragmentOne and it has a TextView. I'm trying create FragmentOne in foreach and add to tabs. I tested code which is in setupViewPager but it doesn't work. How can I edit TextView which in fragments?
if I remove this lines it works but contents of fragment always show default that = "TAB ONE". I want to edit all TextView which is in fragments that created at run time;
View view = fView.getView();
TextView txtTabItemNumber = (TextView)view.findViewById(R.id.txtTabItemNumber);
txtTabItemNumber.setText("TAB " + i);
DynamicTabsActivity.java
public class DynamicTabsActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dynamic_tabs);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
LayoutInflater inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int count = 10;
for (int i=0; i<count; i++){
OneFragment fView = new OneFragment();
View view = fView.getView();
TextView txtTabItemNumber = (TextView)view.findViewById(R.id.txtTabItemNumber);
txtTabItemNumber.setText("TAB " + i);
adapter.addFrag(fView,"TAB " + i);
}
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
activity_dynamic_tabs.xml
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
OneFragment.java
public class OneFragment extends Fragment{
public OneFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_one, container, false);
}
}
fragment_one.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="info.androidhive.materialtabs.fragments.OneFragment">
<TextView
android:id="#+id/txtTabItemNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TAB ONE"
android:textSize="40dp"
android:textStyle="bold"
android:layout_centerInParent="true"/>
</RelativeLayout>
The fragment's layout hasn't been created at point that you call findViewById below:
OneFragment fView = new OneFragment();
View view = fView.getView();
TextView txtTabItemNumber = (TextView)view.findViewById(R.id.txtTabItemNumber);
Following is more typically way this is coded:
public static class OneFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
private int sectionNumber;
public OneFragment() {
}
public static OneFragment newInstance(int sectionNumber) {
OneFragment fragment = new OneFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
TextView textView = (TextView) rootView.findViewById(R.id.txtTabItemNumber);
textView.setText("TAB " + sectionNumber);
return rootView;
}
}
you might also want to move fragment creation in to adapter...for example:
public Fragment getItem(int position) {
return OneFragment.newInstance(position + 1);
}
After trying for long...I came up with the following solution:
DynamicTabsActivity is my main activity, looks like this:
public class DynamicTabsActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPagerAdapter viewPagerAdapter;
private int noOfTabs = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dynamic_tabs);
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), noOfTabs);
viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(viewPagerAdapter);
tabLayout = findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
}
My fragment looks like this:
public class DynamicFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
private int sectionNumber;
public DynamicFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sectionNumber = getArguments() != null ? getArguments().getInt(ARG_SECTION_NUMBER) : 1;
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_dynamic, container, false);
TextView textView = view.findViewById(R.id.txtTabItemNumber);
textView.setText("TAB " + sectionNumber);
return view;
}
public static DynamicFragment newInstance(int sectionNumber) {
DynamicFragment fragment = new DynamicFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
}
My ViewPager Class looks like this:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private int noOfItems;
public ViewPagerAdapter(FragmentManager fm, int noOfItems) {
super(fm);
this.noOfItems = noOfItems;
}
#Override
public Fragment getItem(int position) {
return DynamicFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return noOfItems;
}
#Override
public CharSequence getPageTitle(int position) {
return "TAB "+(position+1);
}
}
DynamicTabsActivity layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DynamicTabsActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.constraint.ConstraintLayout>
Fragment layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DynamicFragment">
<TextView
android:id="#+id/txtTabItemNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="TAB ONE"
android:textSize="40dp"
android:textStyle="bold" />
</RelativeLayout>
Hope it helps...
Try this,
LinearLayout main = new LinearLayout(this);
main.setOrientation(LinearLayout.VERTICAL);
TextView textView = new TextView(this);
textView .setText("TAB " + i);
main .addView(textView );

TabLayout - ViewPager - Fragment

I have a problem with my ViewPager and fragments it contains. I have 2 menus (A and B), my homepage is directly A. When I click on a menu B fragment which contains a TabLayout, which contains a ViewPager himself three fragments (each contains a simple TextView with Lorem ipsum).
The 3 fragments of ViewPager are correct but if I click on the menu A and I click again on the menu B I do not have any content. Nothing on the fragments 1 and 2 against with the 3rd still has the text and if I return to fragment 1 reads income (for nothing against the fragment 2).
Here is my code :
Menu B (FragmentTabLayout)
public class TabLayoutFragment extends Fragment {
private static final String ARG_TEXT = "ARG_TEXT";
private static final String ARG_COLOR = "ARG_COLOR";
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
public TabLayoutFragment() {
// Required empty public constructor
}
public static TabLayoutFragment newInstance(String text, int color) {
Bundle args = new Bundle();
args.putString(ARG_TEXT, text);
args.putInt(ARG_COLOR, color);
TabLayoutFragment tabLayoutFragment = new TabLayoutFragment();
tabLayoutFragment.setArguments(args);
return tabLayoutFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_tab_layout, container, false);
toolbar = (Toolbar) view.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
toolbar.setBackgroundColor(getArguments().getInt(ARG_COLOR));
toolbar.setTitle(getArguments().getString(ARG_TEXT));
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setBackgroundColor(getArguments().getInt(ARG_COLOR));
tabLayout.setSelectedTabIndicatorColor(Color.WHITE);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.tab_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
//private final List<TabFragment> mFragmentList = new ArrayList<>();
//private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return TabFragment.newInstance("Fragment 2-1");
case 1:
return TabFragment.newInstance("Fragment 2-2");
case 2:
return TabFragment.newInstance("Fragment 2-3");
default:
return TabFragment.newInstance("Fragment Default");
}
}
#Override
public int getCount() {
//return mFragmentList.size();
return 3;
}
}
}
Fragment in ViewPager :
public class TabFragment extends Fragment {
private static final String ARG_TEXT = "ARG_TEXT";
private TextView tv;
public TabFragment() {
// Required empty public constructor
}
public static TabFragment newInstance(String text) {
Bundle args = new Bundle();
args.putString(ARG_TEXT, text);
TabFragment tabFragment= new TabFragment();
tabFragment.setArguments(args);
return tabFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_tab, container, false);
tv = (TextView) view.findViewById(R.id.tv);
return view;
}
}
Layout FragmentTabLayout :
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</android.support.design.widget.CoordinatorLayout>
layout tabFragment :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
tools:context="com.application.myapplication.TabFragment">
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
>
<TextView
android:id="#+id/tv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/lorem_ipsum"
/>
</android.support.v4.widget.NestedScrollView>
</LinearLayout>
you can extends your ViewPagerAdapter
FragmentStatePagerAdapter
instead of
FragmentPagerAdapter
I have same issue and it works for me.
In my Opinion the better approach is you should try using childFragmentManager for your nested fragments
Here is the simple example:
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getChildFragmentManager());
viewPager.setAdapter(adapter);
}
Hopefully it will solve your issue.

Replacing fragment with a new fragment in TabLayout

I am newbie to android development. I have 3 fragments in tabview. BlankFragment, Map Fragment and RageComicListFragment. In the RageComicListFragment I want to change the fragment to RageComicDetailsFragment when user click one of the items in the list. But now, when user clicks and image on the RageComicListFragment, RageComicDetailsFragment appears in the screen but old fragment still visible. I searched throught internet and find some reason that might cause this problem. I think, I have to add fragments dynamically to tabview. But I cannot find a proper way to do this in my main activity. My code is like this.
//MainActivity.java.
public class MainActivity extends AppCompatActivity implements MapFragment.OnMarkerClicked, RageComicListFragment.OnRageComicSelected {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Get the ViewPager and set it's PagerAdapter so that it can display items
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
PagerAdapter pagerAdapter
= new PagerAdapter(getSupportFragmentManager(), MainActivity.this);
viewPager.setAdapter(pagerAdapter);
// Give the TabLayout the ViewPager
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
// Iterate over all tabs and set the custom view
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pagerAdapter.getTabView(i));
}
}
#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) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class PagerAdapter extends FragmentPagerAdapter {
String tabTitles[] = new String[]{"Tab One", "Tab Two", "Tab Three",};
Context context;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new BlankFragment();
case 1:
return new MapFragment();
case 2:
return new RageComicListFragment();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
public View getTabView(int position) {
View tab = LayoutInflater.from(MainActivity.this).inflate(R.layout.custom_tab, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
}
#Override
public void OnMarkerClicked(int resId) {
Toast.makeText(this, "Hey, you selected " + resId + "!", Toast.LENGTH_SHORT).show();
final BlankFragment2 detailsFragment
= BlankFragment2.newInstance(resId);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_layout, detailsFragment, "rageComicDetails")
.addToBackStack(null)
.commit();
}
#Override
public void onRageComicSelected(int imageResId, String name, String description, String url) {
final DetailsFragment detailsFragment = DetailsFragment.newInstance(imageResId, name, description, url);
RelativeLayout contentView = (RelativeLayout) this.findViewById(R.id.main_layout);
getSupportFragmentManager()
.beginTransaction()
.replace(contentView.getId(), detailsFragment, "rageComicDetails")
.addToBackStack(null)
.commit();
}
}
//RageComicListFragment.java
public class RageComicListFragment extends Fragment {
private int[] mImageResIds;
private String[] mNames;
private String[] mDescriptions;
private String[] mUrls;
private OnRageComicSelected mListener;
public static RageComicListFragment newInstance() {
return new RageComicListFragment();
}
public RageComicListFragment() {
// Required empty public constructor
}
#Override
public void onAttach(Context context) {
if (context instanceof OnRageComicSelected) {
mListener = (OnRageComicSelected) context;
} else {
throw new ClassCastException(context.toString() + " must implement OnRageComicSelected.");
}
super.onAttach(context);
// Get rage face names and descriptions.
final Resources resources = context.getResources();
mNames = resources.getStringArray(R.array.names);
mDescriptions = resources.getStringArray(R.array.descriptions);
mUrls = resources.getStringArray(R.array.urls);
// Get rage face images.
final TypedArray typedArray = resources.obtainTypedArray(R.array.images);
final int imageCount = mNames.length;
mImageResIds = new int[imageCount];
for (int i = 0; i < imageCount; i++) {
mImageResIds[i] = typedArray.getResourceId(i, 0);
}
typedArray.recycle();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_rage_comic_list, container, false);
final Activity activity = getActivity();
final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new GridLayoutManager(activity, 2));
recyclerView.setAdapter(new RageComicAdapter(activity));
return view;
}
class RageComicAdapter extends RecyclerView.Adapter<ViewHolder> {
private LayoutInflater mLayoutInflater;
public RageComicAdapter(Context context) {
mLayoutInflater = LayoutInflater.from(context);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
return new ViewHolder(mLayoutInflater
.inflate(R.layout.recycler_item_rage_comic, viewGroup, false));
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
final int imageResId = mImageResIds[position];
final String name = mNames[position];
final String description = mDescriptions[position];
final String url = mUrls[position];
viewHolder.setData(imageResId, name);
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.onRageComicSelected(imageResId, name, description, url);
}
});
}
#Override
public int getItemCount() {
return mNames.length;
}
}
class ViewHolder extends RecyclerView.ViewHolder {
// Views
private ImageView mImageView;
private TextView mNameTextView;
private ViewHolder(View itemView) {
super(itemView);
// Get references to image and name.
mImageView = (ImageView) itemView.findViewById(R.id.comic_image);
mNameTextView = (TextView) itemView.findViewById(R.id.name);
}
private void setData(int imageResId, String name) {
mImageView.setImageResource(imageResId);
mNameTextView.setText(name);
}
}
public interface OnRageComicSelected {
void onRageComicSelected(int imageResId, String name,
String description, String url);
}
}
//RageComicDetailsFragment.java
public class RageComicDetailsFragment extends Fragment {
private static final String ARGUMENT_IMAGE_RES_ID = "imageResId";
private static final String ARGUMENT_NAME = "name";
private static final String ARGUMENT_DESCRIPTION = "description";
private static final String ARGUMENT_URL = "url";
public static RageComicDetailsFragment newInstance(int imageResId, String name, String description, String url) {
final Bundle args = new Bundle();
args.putInt(ARGUMENT_IMAGE_RES_ID, imageResId);
args.putString(ARGUMENT_NAME, name);
args.putString(ARGUMENT_DESCRIPTION, description);
args.putString(ARGUMENT_URL, url);
final RageComicDetailsFragment fragment = new RageComicDetailsFragment();
fragment.setArguments(args);
return fragment;
}
public RageComicDetailsFragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_rage_comic_details, container, false);
final ImageView imageView = (ImageView) view.findViewById(R.id.comic_image);
final TextView nameTextView = (TextView) view.findViewById(R.id.name);
final TextView descriptionTextView = (TextView) view.findViewById(R.id.description);
final Bundle args = getArguments();
imageView.setImageResource(args.getInt(ARGUMENT_IMAGE_RES_ID));
nameTextView.setText(args.getString(ARGUMENT_NAME));
final String text = String.format(getString(R.string.description_format), args.getString(ARGUMENT_DESCRIPTION), args.getString(ARGUMENT_URL));
descriptionTextView.setText(text);
return view;
}
}
//content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/main_layout"
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=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
app:tabMode="fixed"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:elevation="6dp"
app:tabTextColor="#d3d3d3"
app:tabSelectedTextColor="#ffffff"
app:tabIndicatorColor="#ff00ff"
android:minHeight="?attr/actionBarSize"
android:layout_alignParentBottom="true"
/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/toolbar"/>
</RelativeLayout>
//fragment_race_comic_list.xml
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"/>
//fragment_race_comic_details.xml
<ScrollView 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:fillViewport="true"
tools:ignore="RtlHardcoded">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/name"
style="#style/TextAppearance.AppCompat.Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="0dp"
android:layout_marginTop="#dimen/rage_comic_name_margin_top"
tools:text="Freddie Mercury"/>
<ImageView
android:id="#+id/comic_image"
android:layout_width="wrap_content"
android:layout_height="#dimen/rage_comic_image_size"
android:layout_marginBottom="#dimen/rage_comic_image_margin_vertical"
android:layout_marginTop="#dimen/rage_comic_image_margin_vertical"
android:adjustViewBounds="true"
android:contentDescription="#null"
android:scaleType="centerCrop"
android:src="#drawable/freddie_mercury"/>
<TextView
android:id="#+id/description"
style="#style/TextAppearance.AppCompat.Body1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="#dimen/rage_comic_description_margin_bottom"
android:layout_marginLeft="#dimen/rage_comic_description_margin_left"
android:layout_marginRight="#dimen/rage_comic_description_margin_right"
android:layout_marginTop="0dp"
android:autoLink="web"
tools:text="Freddie Mercury Rage Pose is a rage comic character made from a photo of deceased British musician and former lead vocalist for the rock band Queen Freddie Mercury. The image is typically used to indicate that an extraordinary feat has been accomplished, similar to the F!## Yea illustration."/>
</LinearLayout>
When replacing or adding fragment dont use the property addto backstack and very first time try to add and next time use replace while performing transaction
e.g
Fragment fragment= DetailImageFetch.newInstance(0,constants.BIG_IMAGE);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container, fragment, "Frag");
transaction.commit();

Android: Can't update textview in Fragment from Activity. NullPointerException

I'm trying to update textview in fragment from another activity. But I'm getting a NUllPointerException when calling the setText method. I have tried the following, but still getting the NPE.
1. Tried accessing the fragments textview with FindViewbyId in activity.
2. Tried using a method in fragment and calling it from activity and passing the value as parameters
FragHome Activity
public class FragHome extends AppCompatActivity implements TabLayout.OnTabSelectedListener {
Handler bluetoothIn;
private static TextView tmpF, humF, CoF;
String tempGL, HumGL, coGL, devname;
double dblTemp, dblCo;
final int handlerState = 0; // used to identify handler message
private BluetoothAdapter btAdapter = null;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frag_home);
//Adding toolbar to the activity
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing the tablayout
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.pager);
//Adding the tabs using addTab() method
tabLayout.addTab(tabLayout.newTab().setText("Temperature"));
tabLayout.addTab(tabLayout.newTab().setText("Humidity"));
tabLayout.addTab(tabLayout.newTab().setText("CO"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//Creating our pager adapter
Pager adapter = new Pager(getSupportFragmentManager(), tabLayout.getTabCount());
//Adding adapter to pager
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
//Adding onTabSelectedListener to swipe views
tabLayout.setOnTabSelectedListener(this);
bluetoothIn=new Handler() {
String readMessage;
String[] values = new String[]{""};
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) {
readMessage = (String) msg.obj;
values = readMessage.split("#");
for (int j = 0; j < values.length; j++) {
int rem = j % 3;
if (rem == 0) {
tmpF.setText(values[j] + " C");
tempGL = String.valueOf(values[j]);
try {
dblTemp = Double.parseDouble(tempGL);
} catch (NumberFormatException e) {
e.printStackTrace();
}
} else if (rem == 1) {
CoF.setText(values[j] + " ppm");
coGL = values[j];
try {
dblCo = Double.parseDouble(coGL);
} catch (NumberFormatException e) {
e.printStackTrace();
}
} else if (rem == 2) {
humF.setText(values[j] + " %");
HumGL = values[j];
}
}
}
}
};
btAdapter=BluetoothAdapter.getDefaultAdapter(); // get Bluetooth
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
// mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
}
Pager
public class Pager extends FragmentStatePagerAdapter {
//integer to count number of tabs
int tabCount;
//Constructor to the class
public Pager(FragmentManager fm, int tabCount) {
super(fm);
//Initializing tab count
this.tabCount= tabCount;
}
//Overriding method getItem
#Override
public Fragment getItem(int position) {
//Returning the current tabs
switch (position) {
case 0:
Tab1 tab1 = new Tab1();
return tab1;
case 1:
Tab2 tab2 = new Tab2();
return tab2;
case 2:
Tab3 tab3 = new Tab3();
return tab3;
default:
return null;
}
}
//Overriden method getCount to get the number of tabs
#Override
public int getCount() {
return tabCount;
}
}
Tab1
public class OneFragment extends Fragment {
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_one, container, false);
return view;
}
}
fragment_one.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="shinil.tablayout.OneFragment"
android:id="#+id/rltnvnv">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Temperature"
android:textSize="40dp"
android:textStyle="bold"
android:id="#+id/textviewtemp"
android:layout_centerInParent="true"/>
</RelativeLayout>
frag_home.xml
LinearLayout
android:id="#+id/main_layout"
android:orientation="vertical"
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=".MainActivity">
<!-- our toolbar -->
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<!-- our tablayout to display tabs -->
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<!-- View pager to swipe views -->
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
The NPE occurs when I try to settext from the activity. Please help
Use below callback:
Fragment Class:
public class FragmentOne extends Fragment {
private ViewCallback mCallback;
public FragmentOne(ViewCallback mCallback) {
this.mCallback = mCallback;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_one, container, false);
mCallback.updateTextView((TextView) view.findViewById(R.id.fragmentTextView));
return view;
}
public interface ViewCallback {
void updateTextView(TextView view);
}
}
Below is the Activity class:
public class MainCallbackActivity extends Activity implements CallbackFragment.ViewCallback {
public TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_callback);
FragmentOne fragment = new FragmentOne(this);
getFragmentManager().beginTransaction().add(R.id.frameLayout, fragment).commit();
}
#Override
protected void onResume() {
super.onResume();
if (textView != null)
textView.setText("Updating Fragment TextView in Activity..!!");
}
#Override
public void updateTextView(TextView view) {
this.textView = view;
}
}
Implment that call back in your activity class..then update the textview.

Categories

Resources