Getting TabLayout view in fragment returns NullPointerException - java

I am trying to add a TabLayout into a fragment, I went over the topic of implementing a TabLayout through multiple tutorials and they were roughly the same. I followed the tutorials and changed a few methods to suit a fragment rather than the usual activity but after compiling it returns an error with getting the Tablayout from the xml file through findViewById. As much as I have checked, then I haven't managed to find what is done wrong. The TabLayout is in a fragment because I am using BottomNavigation for the application's main navigation but i would like to use a TabLayout for displaying extra info inside the fragment.
Here is the Fragment that holds the TabLayout
public class LocationsFragment extends Fragment {
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
//The next line has the NullPointerException.
TabLayout tabLayout = getView().findViewById(R.id.tabLayout);
TabItem discoveredTab = getView().findViewById(R.id.discoveredTab);
TabItem allLocationsTab = getView().findViewById(R.id.allTab);
ViewPager viewPager = getView().findViewById(R.id.viewPager);
PagerAdapter pagerAdapter = new PagerAdapter(getChildFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(pagerAdapter);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
if (tab.getPosition() == 0){
pagerAdapter.notifyDataSetChanged();
} else if (tab.getPosition() == 1){
pagerAdapter.notifyDataSetChanged();
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
View root = inflater.inflate(R.layout.fragment_locations, container, false);
return root;
}
Here is the PagerAdapter class
public class PagerAdapter extends FragmentPagerAdapter {
private int numOfTabs;
public PagerAdapter(FragmentManager fragmentManager, int numOfTabs){
super(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
this.numOfTabs = numOfTabs;
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new TabDiscoveredFragment();
case 1:
return new TabAllFragment();
default:
return null;
}
}
#Override
public int getCount() {
return numOfTabs;
}
}
And here is the layout file
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.journey.JourneyFragment">
<RelativeLayout
android:id="#+id/statLayout"
android:layout_width="match_parent"
android:layout_height="65sp"
android:layout_marginStart="20sp"
android:layout_marginEnd="20sp"
android:layout_marginTop="30sp"
android:background="#drawable/layout_bg_round_all">
//TextViews which are irrelevant to the example
</RelativeLayout>
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/statLayout"
android:layout_marginTop="20sp">
<com.google.android.material.tabs.TabItem
android:id="#+id/discoveredTab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Discovered" />
<com.google.android.material.tabs.TabItem
android:id="#+id/allTab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="All locations" />
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:layout_width="0dp"
android:layout_height="0dp"
android:id="#+id/viewPager">
</androidx.viewpager.widget.ViewPager>
</RelativeLayout>

You can't use getView() in onCreateView() fragment lifecycle method.. because the fragment view is not yet created; actually onCreateView() creates this view and returns it back.
You can only use getView() in fragment lifecycle methods that are after onCreateView()
To solve this you need to use the inflated view itself, to apply that on your code, replace getView() with root... but declare it at the very beginning of the method.
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_locations, container, false);
//The next line has the NullPointerException.
TabLayout tabLayout = root.findViewById(R.id.tabLayout);
TabItem discoveredTab = root.findViewById(R.id.discoveredTab);
TabItem allLocationsTab = root.findViewById(R.id.allTab);
ViewPager viewPager = root.findViewById(R.id.viewPager);
PagerAdapter pagerAdapter = new PagerAdapter(getChildFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(pagerAdapter);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
if (tab.getPosition() == 0){
pagerAdapter.notifyDataSetChanged();
} else if (tab.getPosition() == 1){
pagerAdapter.notifyDataSetChanged();
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
return root;
}

Related

Can't swipe between tabs in TabLayout

I'm able to click the tabs to change, but nothing happens when I swipe. I don't see the coloured bar underneath the selected tab either.
Here's my code. I've largely followed this tutorial, but I've changed tabLayout.setOnTabSelectedListener(this) to tabLayout.addOnTabSelectedListener(this) in StoriesActivity because the former is depreceated.
StoriesActivity:
public class StoriesActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener {
//This is our tablayout
private TabLayout tabLayout;
//This is our viewPager
private ViewPager viewPager;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stories);
/* +++ START Intent +++ */
Bundle extras = getIntent().getExtras();
final int authorID = extras.getInt("author_id");
final String authorName = extras.getString("author_name");
Log.i("click", Integer.toString(authorID));
/* +++ END Intent +++ */
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(authorName);
setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
//Initializing the tablayout
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
//Adding the tabs using addTab() method
tabLayout.addTab(tabLayout.newTab().setText("Stories"));
tabLayout.addTab(tabLayout.newTab().setText("Collections"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.pager);
//Creating our pager adapter
StoriesTabsAdapter adapter = new StoriesTabsAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
//Adding adapter to pager
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
//Adding onTabSelectedListener to swipe views
tabLayout.addOnTabSelectedListener(this);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
}
activity_stories.xml:
<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"
app:navigationIcon="?attr/homeAsUpIndicator"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"/>
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/stories_list_view" />
</RelativeLayout>
StoriesTabsAdapter:
public class StoriesTabsAdapter extends FragmentPagerAdapter {
int mNumOfTabs;
public StoriesTabsAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
StoriesFragment tab1 = new StoriesFragment();
return tab1;
case 1:
CollectionsFragment tab2 = new CollectionsFragment();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
StoriesFragment:
public class StoriesFragment extends Fragment {
public StoriesFragment() {
// Required empty public constructor
}
private ListView storiesListView;
#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_stories, container, false);
}
}
You are missing to setupWithViewPager your TabLayout.
mTabLayout.setupWithViewPager(mViewPager)
Regarding the problem of your text not to be appearing, try to move the code below straight after you setupWithViewPager
//Adding the tabs using addTab() method
tabLayout.addTab(tabLayout.newTab().setText("Stories"));
tabLayout.addTab(tabLayout.newTab().setText("Collections"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
You should follow below two points.
Use FragmentStatePagerAdapter for good approach.
setupWithViewPager
If you're using a ViewPager together with this layout, you can call
setupWithViewPager(ViewPager) to link the two together. This layout
will be automatically populated from the PagerAdapter's page titles.
Secondly
_tablayoutOBJ.setupWithViewPager(_viewpagerOBJ); // After addOnTabSelectedListener .
For, Demo case you can visit Material Design working with Tabs.

Android Fragment Always NULL When Accessing From ViewPagerAdapter

The Problem:
In my onCreate() on my main activity, I am trying to set the text value of a TextView in my fragment which is displayed by a viewpager. When I try to get my fragment instance, It always returns null.
Solutions I Tried:
Almost every solution related to this problem on SO gives me the same result(NPE).
My Code is below as well as some explanation...
Home.java Activity (My Main Activity):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Show the home layout
setContentView(R.layout.home);
// Setup the toolbar
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Now setup our tab bar
TabLayout tabLayout = (TabLayout)findViewById(R.id.homeTabs);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
// Setup the view pager
ViewPager viewPager = (ViewPager)findViewById(R.id.viewPager);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager);
// Start our service controller
Intent startServiceController = new Intent(this, ServiceController.class);
startService(startServiceController);
Fragment viewFragment = pagerAdapter.getRegisteredFragment(viewPager.getCurrentItem());
if(viewFragment == null){
Log.v("Fragment", "NULL");
}
}
After setting up the pageAdapter and viewpager, I try to access the fragment thats being shown. The code for my PagerAdapter is below...
PagerAdapter:
public class PagerAdapter extends SmartFragmentStatePagerAdapter {
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new ParkListFragment();
case 1:
return new MapFragment();
default:
return null;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
CharSequence title;
switch (position){
case 0:
title = "Spaces Near You";
break;
case 1:
title = "Map";
break;
default:
title = "N/A";
break;
}
return title;
}
}
SmartFragmentStatePagerAdapter:
public abstract class SmartFragmentStatePagerAdapter extends FragmentStatePagerAdapter {
// Sparse array to keep track of registered fragments in memory
private SparseArray<Fragment> registeredFragments = new SparseArray<>();
public SmartFragmentStatePagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Register the fragment when the item is instantiated
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
// Unregister when the item is inactive
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
// Returns the fragment for the position (if instantiated)
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
I really don't understand what the issue is. I have tried many things. What I don't want to use is this:
String tag="android:switcher:" + viewId + ":" + index;
ParkListFragment.java:
public class ParkListFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.park_list_fragment, container, false);
}
}
ParkList Fragment 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">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_centerInParent="true">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/confidenceText"
android:textAlignment="center"
android:textSize="24sp"
android:textColor="#android:color/primary_text_light"
android:padding="10dp"/>
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_centerInParent="true">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/activityText"
android:textAlignment="center"
android:textSize="24sp"
android:textColor="#android:color/primary_text_light"
android:padding="10dp"/>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
Stack Trace: Pastebin
So after hours of trial and error, the only thing that worked for me was this SO post:
ViewPager Fragments are not initiated in onCreate

TabLayout on landscape not showing gravity_fill and mode_fixed

I'm using TabLayout and ViewPager together to do a tabbed viewpager.
I've got a weird behavior in landscape where TabLayout.GRAVITY_FILL and TabLayout.MODE_FIXED don't seem to work, regardless of being set in java or xml (they do just fine for portrait).
However! When I do THREE tabs, everything is a-ok!
The problem is with TWO tabs - in landscape.
My Activity:
public class TabbedViewPager extends AppCompatActivity {
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabbed_viewpager);
initTabLayout1();
}
public void initTabLayout1() {
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
TabLayout.Tab tab1 = tabLayout.newTab();
tab1.setText("Tab 1");
tabLayout.addTab(tab1);
TabLayout.Tab tab2 = tabLayout.newTab();
tab2.setText("Tab 2");
tabLayout.addTab(tab2);
//TabLayout.Tab tab3 = tabLayout.newTab();
//tab3.setText("Tab 3");
//tabLayout.addTab(tab3);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
viewPager = (ViewPager) findViewById(R.id.view_pager);
final TabbedPagerAdapter adapter = new TabbedPagerAdapter(getSupportFragmentManager(),
tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {}
#Override
public void onTabReselected(TabLayout.Tab tab) {}
});
}
}
My Fragment, same for both One and Two, (with a blank/bg-colored xml):
public class FragmentOne extends Fragment {
public FragmentOne() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
return view;
}
}
My Adapter:
public class TabbedPagerAdapter extends FragmentStatePagerAdapter {
private int mNumOfTabs;
public TabbedPagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
FragmentOne tab1 = new FragmentOne();
return tab1;
case 1:
FragmentTwo tab2 = new FragmentTwo();
return tab2;
case 2:
FragmentOne tab3 = new FragmentOne();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
My Activity XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_tabbed_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.samp.ling.sampleapp.examples.TabbedViewPager">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="200dp"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:background="#android:color/holo_orange_light"
app:tabIndicatorColor="#android:color/holo_orange_dark"
app:tabIndicatorHeight="5dp"/>
<!--app:tabGravity="fill"-->
<!--app:tabMode="fixed"-->
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
</RelativeLayout>
As seen from above, exact same code besides an extra tab, 2-tabs don't adhere to tablayout's fill/fixed in landscape - why? what's wrong?
Oh, this is with the latest support libraries:
appcompat-v7:25.0.1, support-v4:25.0.1, design:25.0.1
Thanks!
app:tabMaxWidth="0dp" fixed it for landscape
Got the clue from:
https://stackoverflow.com/a/31620690/6668797
just add app:tabMaxWidth="0dp" to layout file
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/main_tablayout"
app:tabGravity="fill"
android:background="#color/colorPrimary"
app:tabIndicatorColor="#color/colorAccent"
app:tabMode="fixed"
app:tabMaxWidth="0dp"
app:tabTextColor="#ffff">
</android.support.design.widget.TabLayout>

How can I add a ViewPager to a Navigation Drawer Item in Android application?

I want to add a viewPager for main fragment in my android app.
This is the xml file for main fragment
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
This is the Java code for Main Fragment
public class MainFragment extends ListFragment {
private static final String TAG = MainFragment.class.getSimpleName();
private StudentsDBHandler studentsDBHandler;
public MainFragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
studentsDBHandler = new StudentsDBHandler(getActivity());
View rootView = inflater.inflate(R.layout.main_fragment, container, false);
displayStudents();
return rootView;
}
private void displayStudents() {
List<Student> studentList = studentsDBHandler.getAll();
ArrayAdapter<Student> list = new ArrayAdapter<>(getActivity(), R.layout.item_student, studentList);
setListAdapter(list);
}
}
You have a DrawerLayout page. It's about your drawer contains.
İn the DrawerLayout XML
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
add this code below
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
write this code and setup your View pager like example
viewPager=(ViewPager)findViewById(R.id.viewPager);
FragmentManager fm=getSupportFragmentManager();
viewPager.setAdapter(new MyAdapter(fm));
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if(position==0)
fragment= new Home1();
if(position==1)
fragment=new Home2();
return fragment;
}
#Override
public int getCount() {
return 2;
}
}
}
I hope Help you

accessing fragment's view from activity with function

I am trying to dynamically change a text from a fragment textview inside de activity but I keep getting 'cannot obtain root' error. I tried to instantiate the textview inside onCreateView and inside onActivityCreated as well but it doesnt work. How can I change the text from a fragment textview inside the activity?
Fragment xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Tab 1"
android:textAppearance="?android:attr/textAppearanceLarge"/>
</RelativeLayout>
Fragment Code:
public class TabFragment1 extends Fragment {
private TextView tv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_fragment_1, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tv = (TextView) getView().findViewById(R.id.textView);
}
public void setText(String text){
tv.setText(text);
}
}
Main xml:
<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"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"/>
</RelativeLayout>
Main code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
TabFragment1 t1 = new TabFragment1();
TabFragment2 t2 = new TabFragment2();
TabFragment3 t3 = new TabFragment3();
adapter.newFrag(t1);
adapter.newFrag(t2);
adapter.newFrag(t3);
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
t1.setText("HELLO WORLD");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
PagerAdapter:
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
List<Fragment> aFrag;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
aFrag = new ArrayList<Fragment>();
}
public void newFrag(Fragment f){
aFrag.add(f);
}
#Override
public Fragment getItem(int position) {
return aFrag.get(position);
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
You try to set text on view, but this view wasn't created, this fragment wasn't created. If You want to set text from activity you can pass bundle to fragment arguments with that text, and in fragment chceck bundle and set text. Later if you want to change text in this fragment then you can use your function.
public class TabFragment1 extends Fragment {
private TextView tv;
public static TabFragment1 create(String text){
Bundle b = new Bundle();
b.putString("textdata",text);
TabFragment1 f = new TabFragment1();
f.setArguments(b);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_fragment_1, container, false);
tv = (TextView) view.findViewById(R.id.textView);
if(getArguments()!=null){
tv.setText(getArguments().getString("textdata"));
}
return view;
}
public void setText(String text){
tv.setText(text);
}
}
In your activity create this fragment using static method:
TabFragment1 t1 =TabFragment1.create("HELLO WORLD");
Hardcore execution of your base code is:
new Handler().postDelayed(new Runnable(){t1.setText("HELLO WORLD");},300);

Categories

Resources