TabLayout.OnTabSelectedListener has one callback which is onTabReselected(TabLayout.Tab tab)
We can reselect tab manually by tapping on selected tab again.
So my question is how to reselect tab programatically?
This is how I got my tabs working
Layout for tabs:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#ffffff">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_scrollFlags="scroll|enterAlways"
app:layout_collapseMode="pin"
android:background="#000000"
app:titleTextColor="#ffffff"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/PopupMenuStyle">
<TextView
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:id="#+id/textview"
android:textColor="#color/colorTrueWhite"/>
</android.support.v7.widget.Toolbar>
<!-- 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="#color/colorBlack"
android:minHeight="?attr/actionBarSize"
app:tabIndicatorColor="#color/colorTrueWhite"
app:tabIndicatorHeight="5dp"
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>
Activity using that layout:
public class Main2Activity extends AppCompatActivity implements TabLayout.OnTabSelectedListener {
private TabLayout tabLayout;
public static ViewPager viewPager;
public static Context ctx;
Pager adapter;
public static int expired, paid;
Boolean isConnection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar tb = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(tb);
TextView tv = (TextView) findViewById(R.id.textview);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ctx = getApplicationContext();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
viewPager = (ViewPager) findViewById(R.id.pager);
tabLayout.addTab(tabLayout.newTab().setText("title1"));
tabLayout.addTab(tabLayout.newTab().setText("title2"));
tabLayout.addTab(tabLayout.newTab().setText("title3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(viewPager);
adapter = new Pager(getSupportFragmentManager(), tabLayout.getTabCount(), ctx);
viewPager.setAdapter(adapter);
if(some condition)
{
viewPager.setCurrentItem(2);
}
else
{
viewPager.setCurrentItem(1);
}
viewPager.setOffscreenPageLimit(2);
tabLayout.addOnTabSelectedListener(this);
ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0);
int tabsCount = vg.getChildCount();
for (int j = 0; j < tabsCount; j++) {
ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
int tabChildsCount = vgTab.getChildCount();
for (int i = 0; i < tabChildsCount; i++) {
View tabViewChild = vgTab.getChildAt(i);
if (tabViewChild instanceof TextView) {
((TextView) tabViewChild).setTypeface(Typeface.DEFAULT, Typeface.BOLD);
}
}
}
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
}
Pager code:
public class Pager extends FragmentStatePagerAdapter
{
int tabcount;
Context ctx;
private String [] Titles = {"title1", "title2", "title3"};
public Pager(FragmentManager fm, int tabcount, Context ctx)
{
super(fm);
this.tabcount = tabcount;
this.ctx = ctx;
}
#Override
public int getCount() {
return tabcount;
}
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
#Override
public Fragment getItem(int position) {
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;
}
}
}
Related
I need to create a dynamic tabhost, which involves, adding and removing tabs dynamically. I'm able to add and remove tabs dynamically. But I need to have delete button in each tab. Also need to differentiate the click for tab click and delete tab click. Kindly refer the image. I have googled to add button to each tab, couldn't find any help.
Edit:
I have added custom view to tablayout. But I need to perform, click on close button to remove the tab. I have figured how to how to add and remove a tab. But I couldn't figure out how to get the click listener for the close button.
custom_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#string/font_fontFamily_medium"
android:gravity="center_horizontal"
android:textColor="#color/colorAccent"
android:textSize="#dimen/tab_label" />
<Button
android:background="#drawable/close"
android:id="#+id/btnClose"
android:layout_width="40dp"
android:layout_height="40dp"
/>
</LinearLayout>
MainActivity and Adapter:
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);
setupTabIcons();
}
/**
* Adding custom view to tab
*/
private void setupTabIcons() {
View rootView1 = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
TextView tabOne = rootView1.findViewById(R.id.tab);
tabOne.setText("ONE");
tabLayout.getTabAt(0).setCustomView(rootView1);
View rootView2 = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
TextView tabTwo = rootView2.findViewById(R.id.tab);
tabTwo.setText("TWO");
tabLayout.getTabAt(1).setCustomView(rootView2);
View rootView3 = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
TextView tabThree = rootView3.findViewById(R.id.tab);
tabThree.setText("THREE");
tabLayout.getTabAt(2).setCustomView(rootView3);
}
/**
* Adding fragments to ViewPager
*
* #param viewPager
*/
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new OneFragment(), "ONE");
adapter.addFrag(new TwoFragment(), "TWO");
adapter.addFrag(new ThreeFragment(), "THREE");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
private String tabTitles[] = new String[]{"Tab1", "Tab2", "Tab3"};
private int[] imageResId = {R.drawable.ic_tab_contacts, R.drawable.ic_tab_call, R.drawable.ic_tab_favourite};
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_main.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="#dimen/custom_tab_layout_height"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
Create Click listener,
View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case 1:
Toast.makeText(CircleActivity.this, "1", Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(CircleActivity.this, "2", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(CircleActivity.this, "Default", Toast.LENGTH_SHORT).show();
break;
}
}
};
Modify your setupTabIcons() method i just remove some boilerplate code,
private void setupTabIcons() {
String[] arrTabTile = new String[]{"ONE", "TWO", "THREE"};
for (int i = 0; i < arrTabTile.length; i++) {
View rootView = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
TextView tabOne = rootView.findViewById(R.id.tab);
tabOne.setText(arrTabTile[i]);
Button btnClose = rootView.findViewById(R.id.btnClose);
btnClose.setId(i + 1);
btnClose.setOnClickListener(onClickListener);
tabLayout.getTabAt(i).setCustomView(rootView);
}
}
Here is explanation:
btnClose.setId(i + 1);//use to idntify uniq button
btnClose.setOnClickListener(onClickListener);//assign click listener
You have almost implemented the solution yourself. Based on your code, adding a different click listener per button can be achieved with something like this:
private void setupTabIcons() {
View rootView1 = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
TextView tabOne = rootView1.findViewById(R.id.tab);
Button buttonOne = rootView1.findViewById(R.id.btnClose);
tabOne.setText("ONE");
tabLayout.getTabAt(0).setCustomView(rootView1);
View rootView2 = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
TextView tabTwo = rootView2.findViewById(R.id.tab);
Button buttonTwo = rootView2.findViewById(R.id.btnClose);
tabTwo.setText("TWO");
tabLayout.getTabAt(1).setCustomView(rootView2);
View rootView3 = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
TextView tabThree = rootView3.findViewById(R.id.tab);
Button buttonThree = rootView3.findViewById(R.id.btnClose);
tabThree.setText("THREE");
tabLayout.getTabAt(2).setCustomView(rootView3);
buttonOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(Main2Activity.this, "Button One clicked!", Toast.LENGTH_SHORT).show();
}
});
buttonTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(Main2Activity.this, "Button Two clicked!", Toast.LENGTH_SHORT).show();
}
});
buttonThree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(Main2Activity.this, "Button Three clicked!", Toast.LENGTH_SHORT).show();
}
});
}
Much like you can get a reference to the TextView per custom view and change its text, you can get a reference to the corresponding button and set a custom click listener. If you just replace your setupTabIcons() with the provided method, when you click each close button you will get a different error message displayed on the screen.
I have Just create Small Programme to Remove tab and also remove fragment layout on image view click for better understanding check out code:
Removable tab layout
activity_main.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.AppBarLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize"
android:padding="#dimen/activity_horizontal_margin"
android:orientation="vertical">
<Button
android:id="#+id/btnScrollableTabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/btn_scrollable_tabs"
android:layout_marginTop="#dimen/btn_margin_top"
android:textSize="15dp" />
</LinearLayout>
MainActivity.java:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Toolbar toolbar;
private Button btnScrollableTabs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
btnScrollableTabs = (Button) findViewById(R.id.btnScrollableTabs);
btnScrollableTabs.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnScrollableTabs:
startActivity(new Intent(MainActivity.this, ScrollableTabsActivity.class));
break;
}
}
}
activity_scrollabel_tab.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" />
ScrollableTabsActivity and ViewPager :
public class ScrollableTabsActivity extends AppCompatActivity {
int NumberOfTab = 5;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
ViewPagerAdapter adapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrollable_tabs);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
adapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
int length = tabLayout.getTabCount();
for (int i = 0; i < length; i++) {
tabLayout.getTabAt(i).setCustomView(getTabView(i));
}
}
public View getTabView(final int position) {
View view = LayoutInflater.from(this).inflate(R.layout.close_tablayout, null);
TextView title = (TextView) view.findViewById(R.id.title);
ImageView icon = (ImageView) view.findViewById(R.id.close);
title.setText(adapter.getPageTitle(position));
icon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NumberOfTab = NumberOfTab - 1;
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
if (tabLayout.getTabCount()==3)
tabLayout.setTabMode(TabLayout.MODE_FIXED);
int length = tabLayout.getTabCount();
for (int i = 0; i < length; i++) {
tabLayout.getTabAt(i).setCustomView(getTabView(i));
}
}
});
return view;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
final Fragment result;
switch (position) {
case 0:
// First Fragment of First Tab
result = new OneFragment();
break;
case 1:
// First Fragment of Second Tab
result = new TwoFragment();
break;
case 2:
// First Fragment of Second Tab
result = new ThreeFragment();
break;
case 3:
// First Fragment of Second Tab
result = new FourFragment();
break;
case 4:
// First Fragment of Second Tab
result = new FiveFragment();
break;
default:
result = null;
break;
}
// Log.d("RESULT",result.getTag());
return result;
}
#Override
public int getCount() {
return NumberOfTab;
}
#Override
public CharSequence getPageTitle(final int position) {
switch (position) {
case 0:
return "One";
case 1:
return "Two";
case 2:
return "Three";
case 3:
return "Four";
case 4:
return "Five";
default:
return null;
}
}
}
}
custom_tabs_layout.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/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Title"
android:textColor="#color/windowBackground">
</TextView>
<ImageView
android:id="#+id/close"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_margin="4dp"
android:layout_toEndOf="#+id/title"
android:layout_toRightOf="#+id/title"
android:src="#drawable/ic_close_black_24dp">
</ImageView>
I am trying to add View Pager in Fragment Class. I have tried all stuff.
public class MessageFragment extends android.support.v4.app.Fragment{
private ViewPager viewPager;
private TabLayout tabLayout;
public static MessageFragment newInstance() {
MessageFragment fragment = new MessageFragment();
Log.d("Click", "newInstance: ");
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_message, container, false);
ViewPager viewPager=(ViewPager)view.findViewById(R.id.viewpager);
if(viewPager!=null)
{
setUpViewPager(viewPager);
}
TabLayout tabLayout = (TabLayout)view. findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabTextColors(getResources().getColorStateList(R.color.colorToolbar));
return view;
}
private void setUpViewPager(ViewPager viewPager)
{
Adapter adapter=new Adapter(getActivity().getSupportFragmentManager());
adapter.addFragment(new TabTaskFragment(),"Tasks");
adapter.addFragment(new TabChatFragment(),"Chat");
viewPager.setAdapter(adapter);
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
}
Here is my xml file, I have added all viewpager code over here
please find
XML FILE:
<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:id="#+id/appbar"
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="wrap_content"
android:visibility="gone"
app:layout_scrollFlags="scroll|enterAlways|snap"
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"
android:background="#color/white"
app:tabIndicatorColor="#color/colorToolbar"
app:tabTextAppearance="#android:style/TextAppearance.Widget.TabWidget"
app:tabTextColor="#color/colorToolbar" />
</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" />
How can I add?
I am not able to fix it.
Tabs will show 1st time, but when the user clicks on any bottom tab than tabs description gone and its show blank screens.
I have tried all stuffs disappointed at last.
Your class file should like this
public class ViewPagerFragment extends Fragment {
ViewPager viewPager;
PagerAdapter mPagerAdapter;
TabLayout tabLayout;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.myLayout, null);
viewPager = (ViewPager) view.findViewById(R.id.transactions_recharge);
mPagerAdapter = new ViewPagerAdapter(getChildFragmentManager(), 7);
viewPager.setAdapter(mPagerAdapter);
tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
return view;
}
class ViewPagerAdapter extends FragmentPagerAdapter {
int pageCount = 0;
String titles[] = {"One", "Two", "Three"};
ViewPagerAdapter(FragmentManager manager, int _pageCount) {
super(manager);
pageCount = _pageCount;
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
//load fragment one
return new FragmentOne();
} else if (position == 1) {
//load fragment two
} else if (position == 2) {
//load fragment three
}
}
#Override
public int getCount() {
return pageCount;
}
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
}
And your XML should me like this.
<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:id="#+id/content_layout"
android:layout_height="match_parent"
android:background="#color/primary">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="#color/white"
app:tabIndicatorHeight="2dp"
app:tabMode="scrollable" />
<android.support.v4.view.ViewPager
android:id="#+id/transactions_recharge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tabs"
android:background="#android:color/transparent">
</android.support.v4.view.ViewPager>
</RelativeLayout>
I currently have this tab view which I followed from this tutorial. Everything works fine until I noticed that the onCreateView is not called on any of the tab. I've looked around here and there for solution but I still can't solve.
Here is my code:
activity_pref_main_container.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=".PrefActivityMain">
<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>
PrefMainActivity.class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pref_main_container);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(R.string.preference_title);
setSupportActionBar(toolbar);
new PrefActivityListAsync(this,this,specialization).execute();
new PrefActivityListAsync(this,this,position).execute();
new PrefActivityListAsync(this,this,type).execute();
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Specialization"));
tabLayout.addTab(tabLayout.newTab().setText("Position"));
tabLayout.addTab(tabLayout.newTab().setText("Type"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PrefAdapter adapter = new PrefAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.setOffscreenPageLimit(2);
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) {
}
});
}
PrefAdapder.class
public class PrefAdapter extends FragmentPagerAdapter {
int mNumOfTabs;
public PrefAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
PrefActivitySpecialization tab1 = new PrefActivitySpecialization();
return tab1;
case 1:
PrefActivityPosition tab2 = new PrefActivityPosition();
return tab2;
case 2:
PrefActivityType tab3 = new PrefActivityType();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return 0;
}
}
one out of three fragment class
PrefActivitySpecialization.class
public class PrefActivitySpecialization extends
android.support.v4.app.Fragment {
private ArrayList<DataPrefSpecialization> dataPrefSpecializationArrayList;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, Bundle savedInstanceState) {
View view =
inflater.inflate(R.layout.activity_pref_specialization_container, container,
false);
dataPrefSpecializationArrayList = ((PrefActivityMain)
getActivity()).getDataPrefSpecialization();
for(int i = 0; i < dataPrefSpecializationArrayList.size(); i++){
Log.d("Check Specialization
",dataPrefSpecializationArrayList.get(i).getName());
}
return inflater.inflate(R.layout.activity_pref_specialization_container, container, false);
}
}
You should make changes at two place:
1) Change
#Override
public int getCount() {
return 0;
}
to
#Override
public int getCount() {
return mNumOfTabs;
}
2) Change
return inflater.inflate(R.layout.activity_pref_specialization_container, container, false);
to
return view;
public PrefAdapter(FragmentManager fm, int NumOfTabs)
You must declare Count No NumOfTabs
int getCount ()-> How many items are in the data set represented by this
Adapter.
#Override
public int getCount()
{
return mNumOfTabs;
}
Do not'
return inflater.inflate(R.layout.activity_pref_specialization_container, container, false);
Do
return view ;
Your getCount() method is returning 0;
There is another (possibly easier) way to connect the view pager with the tab layout-
First, in your PrefAdapter class, override the getPageTitle() method and return your tab titles for the respective tab positions from there.
In your PrefMainActivity class, remove all the lines like-
tabLayout.addTab(...)
Add the following line instead-
tabLayout.setupWithViewPager(viewPager);
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.
There's something wrong with my TabLayout and ViewPager. It does not show anything. Here's my adapter:
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int mNumOfTabs) {
super(fm);
this.mNumOfTabs = mNumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return ChoiceFragment.newInstance("Mobile Games",
R.drawable.ic_stay_current_portrait_white_48dp, "1");
case 1:
return ChoiceFragment.newInstance("Computer Games",
R.drawable.ic_payment_white_48dp, "5");
default: return ChoiceFragment.newInstance("Mobile Games",
R.drawable.ic_stay_current_portrait_white_48dp, "1");
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
#Override
public CharSequence getPageTitle(int position) {
String title;
if (position == 0)
title = "Mobile";
else
title = "Computer";
return title;
}
Here's my TabFragment class:
public class TabGroupFragment extends Fragment {
public TabGroupFragment() {
// Required empty public constructor
}
public static TabGroupFragment newInstance() {
TabGroupFragment fragment = new TabGroupFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tab_group, container, false);
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Mobile"));
tabLayout.addTab(tabLayout.newTab().setText("Computer"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) view.findViewById(R.id.view_pager);
final PagerAdapter adapter = new PagerAdapter(
getActivity().getSupportFragmentManager(),
tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(
new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return view;
}
}
And here's the layout for the above class:
FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".TabGroupFragment">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/utility_white"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:id="#+id/tab_layout" />
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/view_pager"/>
</LinearLayout>
</ScrollView>
I don't see any wrong here. I just followed the tutorial. Let me know what's happening here. Thank you
Thanks #MikeM. it all worked now. I removed the LinearLayout surrounding the TabLayout and ViewPager and changed the FrameLayout to RelativeLayout and they all showed up. Thank you!
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".TabGroupFragment">
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/utility_white"
android:elevation="6dp"
android:id="#+id/tab_layout" />
<android.support.v4.view.ViewPager
android:layout_below="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/view_pager"/>
</RelativeLayout>