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>
Related
actvity_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.design.widget.TabLayout
android:id="#+id/tabs"
android:background="#ef9f9f"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed" />
</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>
// MainActivity :
public class MainActivity extends AppCompatActivity {
private TabLayout tabLayout;
public ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
View headerView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.custom_tab, null, false);
final LinearLayout linearLayoutOne = (LinearLayout) headerView.findViewById(R.id.ll);
final LinearLayout linearLayout2 = (LinearLayout) headerView.findViewById(R.id.ll2);
final TextView text1 = (TextView) headerView.findViewById(R.id.tvtab1);
final TextView text2 = (TextView) headerView.findViewById(R.id.tvtab2);
tabLayout.getTabAt(0).setCustomView(linearLayoutOne);
tabLayout.getTabAt(1).setCustomView(linearLayout2);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (tab.getText().equals("ONE")) {
text1.setVisibility(View.VISIBLE);
} else {
text2.setVisibility(View.VISIBLE);
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
if (tab.getText().equals("ONE")) {
text1.setVisibility(View.GONE);
} else {
text2.setVisibility(View.GONE);
}
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "ONE");
adapter.addFragment(new TwoFragment(), "TWO");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
This is my code I want to set custom tab like when i select the first tab then indicator and tab width or weight of the first tab I should increase and second tab decrease show only image not text same if we select the second tab then first tab indicator or weight should decrease and second tab text and image should visibility on:
my current Screen:
in this u can see that tab one is selected image and text are visible tab second is not unselected so the only image is visible no text:
but my Expected tab is like this :
look in this when we select tab then indicator and width of tab increase and tab 2 decreases please suggest me how I will achieve this .thanx
you can easily achieve custom tab with tab layout,
try this one:
public void setupTabView(){
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setCustomView(R.layout.custom_tab);
TextView tab_name = (TextView) tabLayout.getTabAt(i).getCustomView().findViewById(R.id.txt_tab_name);
tab_name.setText("" + tabNames[i]);
}
}
And make one drawable file with name custom_tab:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/txt_tab_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="14sp" />
</RelativeLayout>
Use Below Code .It is have two option.
(i) Create custom TabLayout
(ii) Change custom tablayout text color
(i) Custom TabLayout
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/tab"
android:layout_width="match_parent"
android:textSize="15sp"
android:gravity="center"
android:textColor="#color/txtbox_text_color_darek"
android:layout_height="match_parent"
/>
Source code is:
TextView tabOne = (TextView)
LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabOne.setText("KPIs" + " ");
tabOne.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.alert_gray,
0);
Objects.requireNonNull(tabLayout.getTabAt(4)).setCustomView(tabOne);
(II) Change Color
private void custom_tablayout_select_unselected_four(final TextView tabOne) {
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (Objects.requireNonNull(tabLayout.getTabAt(4)).isSelected()) {
tabOne.setTextColor(getResources().getColor(R.color.text_color_darkblue));
} else {
tabOne.setTextColor(getResources().getColor(R.color.txtbox_text_color_darek));
}
}
#Override`
public void onTabUnselected(TabLayout.Tab tab) {
// tabOne.setTextColor(Color.GREEN);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
// tabOne.setTextColor(Color.GREEN);
}
});
}
I copied the solution from here, Maybe it will be useful for you
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
TabHost mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec("tab_test1")
.setIndicator((""),getResources().getDrawable(R.drawable.mzl_05))
.setContent(new Intent(this, NearBy.class)));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2")
.setIndicator((""),getResources().getDrawable(R.drawable.mzl_08))
.setContent(new Intent(this, SearchBy.class)));
mTabHost.setCurrentTab(0);
mTabHost.getTabWidget().getChildAt(0).setLayoutParams(new
LinearLayout.LayoutParams((width/2)-2,50));
mTabHost.getTabWidget().getChildAt(1).setLayoutParams(new
LinearLayout.LayoutParams((width/2)-2,50));
You can try another code tabHost.getTabWidget().getChildAt(0).getLayoutParams().width = 50;
Create Custom tab layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="48dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="horizontal">
<TextView
android:id="#+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#drawable/tab_text_color_selector"
android:textSize="#dimen/medium_text"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_count"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_marginStart="4dp"
android:background="#drawable/badge_background"
android:gravity="center"
android:textColor="#color/colorPrimary"
android:textSize="#dimen/medium_text"
android:textStyle="bold"
android:visibility="gone" />
</LinearLayout>
tabTitles = new String[]{getString(R.string.main_tab_call), getString(R.string.main_tab_chat), getString(R.string.main_tab_contact)};
private void setupTabIcons() {
for (int i = 0; i < tabTitles.length; i++) {
mTabLayout.getTabAt(i).setCustomView(prepareTabView(i));
}
}
private View prepareTabView(int pos) {
View view = getLayoutInflater().inflate(R.layout.custom_tab, null);
TextView tv_title = view.findViewById(R.id.tv_title);
TextView tv_count = view.findViewById(R.id.tv_count);
tv_title.setText(tabTitles[pos]);
return view;
}
I am working on an Android app, that would have 4 tabs with 4 fragments. I have run the app on my Android device. But the problem I am encountering is that, when I click on the first 2 tabs, it works fine, but when I open the 3rd and 4th tab, APP CRASHES IMMEDIATELY!
Initially, I thought there was a bug on the 3rd and 4th fragments, but I later discovered that this is not a 3rd or 4th fragment bug. I replaced the 1st and 2nd fragments with the 3rd and 4th fragment, and the 1st and 2nd fragments replaced with the 3rd and 4th fragments. And the same thing still happened!
This is my main_activity.java.
public class Main_activity extends AppCompatActivity {
#Bind(R.id.main_activity)
View mView;
private int[] tabIcons = {
R.drawable.friend_chat,
R.drawable.call,
R.drawable.tab_contact,
R.drawable.profile
};
private TabLayout tabLayout;
private FragmentManager mFragmentManager;
private FragmentTransaction mFragmentTransaction;
private NonSwipeableViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.viewpager, new ConversationsFragment()).commit();
viewPager = (NonSwipeableViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
tabLayout.getTabAt(3).setIcon(tabIcons[3]);
int tabIconColor = ContextCompat.getColor(Main_Intergister.this, R.color.holo_red_dark);
tabLayout.getTabAt(0).getIcon().setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);
tabLayout.getTabAt(1).getIcon().setColorFilter(Color.parseColor("#a0a3a7"), PorterDuff.Mode.SRC_IN);
tabLayout.getTabAt(2).getIcon().setColorFilter(Color.parseColor("#a0a3a7"), PorterDuff.Mode.SRC_IN);
tabLayout.getTabAt(3).getIcon().setColorFilter(Color.parseColor("#a0a3a7"), PorterDuff.Mode.SRC_IN);
ColorStateList colors;
if (Build.VERSION.SDK_INT >= 23) {
colors = getResources().getColorStateList(R.color.ash, getTheme());
}
else {
colors = getResources().getColorStateList(R.color.ash);
}
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
assert tab != null;
Drawable icon = tab.getIcon();
if (icon != null) {
icon = DrawableCompat.wrap(icon);
DrawableCompat.setTintList(icon, colors);
}
}
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
tab.getIcon().setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);
switch (tab.getPosition()) {
case 0:
viewPager.setCurrentItem(0);
break;
case 1:
viewPager.setCurrentItem(1);
break;
case 2:
viewPager.setCurrentItem(2);
case 3:
viewPager.setCurrentItem(3);
break;
default:
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
tab.getIcon().setColorFilter(Color.parseColor("#a0a3a7"), PorterDuff.Mode.SRC_IN);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void setupViewPager(NonSwipeableViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new ConversationsFragment(), "Chats");
adapter.addFragment(new ContactsFragment(), "Calls");
adapter.addFragment(new CallsFragment(), "Contacts");
adapter.addFragment(new Profile_fragment(), "Profile");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return null;
}
}
}
This is my main_activity.xml.
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_activity"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:fitsSystemWindows="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay"
android:id="#+id/appbar">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardElevation="4dp"
card_view:cardCornerRadius="0dp">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:id="#+id/toolbar"
android:layout_height="?attr/actionBarSize"
android:background="#color/white"
app:layout_scrollFlags="scroll|enterAlways"
app:elevation="6dp"
app:popupTheme="#style/AppTheme.PopupOverlay">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/toolbar_app_name"
android:text="#string/app_name"
android:textColor="#color/holo_red_dark"
android:textSize="30sp"
android:textStyle="bold"/>
</android.support.v7.widget.Toolbar>
</android.support.v7.widget.CardView>
</android.support.design.widget.AppBarLayout>
<com.solid.helpers.NonSwipeableViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardElevation="4dp"
card_view:cardCornerRadius="0dp">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabIndicatorColor="#color/white"
app:tabIndicatorHeight="8dp"
app:elevation="6dp"
app:tabGravity="fill"
android:background="#color/white"/>
</android.support.v7.widget.CardView>
</LinearLayout>
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
Since you have 4 tabs, please try adding the following code under main_activity onCreate event and see would it solve your issue.
viewpager.setOffscreenPageLimit(4);
I have created an app with a Tabbed Activity. I have 3 Tabs and in the first tab I have added a RecyclerView. At first everything works fine. But when I start the app now, the fragments are empty. Even the fragments of the 2nd and 3rd Tabs are empty, where I only placed a TextView. Here is the code from the MainActivity, it is mainly generated from Android Studio, I only added some code to change the Toolbar title and changed some small things:
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Pflege");
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.tab_icon_pflege);
tabLayout.getTabAt(1).setIcon(R.drawable.tab_icon_dokumentation);
tabLayout.getTabAt(2).setIcon(R.drawable.tab_icon_probleme);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
switch(tab.getPosition()) {
case 0:
mViewPager.setCurrentItem(0);
toolbar.setTitle("Pflege");
break;
case 1:
mViewPager.setCurrentItem(1);
toolbar.setTitle("Daten");
break;
case 2:
mViewPager.setCurrentItem(2);
toolbar.setTitle("Probleme");
break;
default:
mViewPager.setCurrentItem(tab.getPosition());
toolbar.setTitle("Pflege");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#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);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position){
case 0:
Tab1Pflege tab1 = new Tab1Pflege();
return tab1;
case 1:
Tab2Dokumentation tab2 = new Tab2Dokumentation();
return tab2;
case 2:
Tab3Probleme tab3 = new Tab3Probleme();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Pflege";
case 1:
return "Daten";
case 2:
return "Probleme";
}
return null;
}
}
}
Here is the XML File for the MainActivity. I changed a bit, that the tabs will be placed at the bottom of the screen:
<?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"
tools:context="eis1617.muellerkimmeyer.app.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay"
android:background="#3f84dd">
<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:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_above="#+id/tabs" />
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:elevation="80dp"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="56dp"
android:clickable="true"
app:tabGravity="fill"
app:tabIndicatorHeight="0dp"
app:tabMode="fixed"
app:tabBackground="#drawable/tab_color_selector"
android:background="#3f84dd"/>
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
Now here is the fragment for the first tab. It contains the RecyclerView:
public class Tab1Pflege extends Fragment {
private RecyclerView recyclerView;
private RecyclerView.Adapter rvAdapter;
private RecyclerView.LayoutManager rvLayoutManager;
private ArrayList<String> listItems;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1_pflege, container, false);
listItems = new ArrayList<>();
listItems.add("Test1");
listItems.add("Test2");
listItems.add("Test3");
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
rvLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(rvLayoutManager);
rvAdapter = new RvAdapter(listItems);
recyclerView.setAdapter(rvAdapter);
return rootView;
}
}
And here is the XML File for that tab:
<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="eis1617.muellerkimmeyer.app.MainActivity">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recyclerView"
/>
</RelativeLayout>
And here the XML file for the list items. There is a TextView on the left and an ImageView on the right:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="?attr/selectableItemBackground">
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/itemTitle"
android:layout_marginLeft="21dp"
android:layout_marginStart="21dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="20sp" />
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/itemImage"
android:layout_marginRight="11dp"
android:layout_marginEnd="11dp"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
And finally here is my Adapter class for the RecyclerView:
public class RvAdapter extends RecyclerView.Adapter<RvAdapter.MyViewHolder> {
ArrayList<String> listItems;
public RvAdapter (ArrayList<String> listItems){
this.listItems = listItems;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_item_layout, null);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.itemTitle.setText(listItems.get(position));
holder.itemImage.setImageResource(R.drawable.ic_keyboard_arrow_right);
}
#Override
public int getItemCount() {
return listItems.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView itemTitle;
ImageView itemImage;
public MyViewHolder(View itemView){
super(itemView);
itemTitle = (TextView) itemView.findViewById(R.id.itemTitle);
itemImage = (ImageView) itemView.findViewById(R.id.itemImage);
}
}
}
I have already tried to replace "extends FragmentPagerAdapter" in MainActivity with "extends FragmentStatePagerAdapter". But the fragments are still empty. Someone know what could be the problem? Sometimes when I change something for example in the XML file for the list items, it works again. But when I restart the app it didnt work anymore. Looks like it is random if it works or not.
Hello all I simply want to achieve this.But I am not being able to achieve this
I did this to achieve this
<?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"
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="wrap_content"
android:background="#42474b"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
<ImageView
android:id="#+id/toolbarlogo"
android:src="#mipmap/toolbarlogo"
android:layout_width="wrap_content"
android:layout_marginRight="200dp"
android:layout_height="46dp"
/>
</android.support.v7.widget.Toolbar>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#494e51"
android:gravity="center_vertical"
android:paddingLeft="40dp"
android:textSize="10dp"
android:textColor="#fff"
android:text="The Ongoing survey closes on Dec 31,2016 at 2:00pm GMT"
/>
<View
android:layout_width="match_parent"
android:layout_height="5dp"
android:background="#fff"/>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabTextAppearance="#style/MineCustomTabText"
app:tabMode="fixed" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:background="#drawable/innerpg_bg"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
and this is my class file
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ongoing,
R.drawable.upcoming,
R.drawable.results
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setPadding(0, getStatusBarHeight(), 0, 0);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
for(int i=0; i < tabLayout.getTabCount(); i++) {
View tab = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(i);
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) tab.getLayoutParams();
p.setMargins(10, 10, 50, 30);
tab.requestLayout();
}
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new Ongoing(), "Ongoing");
adapter.addFrag(new Upcomming(), "Upcomming");
adapter.addFrag(new Result(), "Result");
viewPager.setAdapter(adapter);
}
public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
return true;
}
return super.onOptionsItemSelected(item);
}
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);
}
}
}
Using above code I am getting tab text below the icon(i mean in two different line).THe next issue is I have set the margin but I dont know how to set the color of margin.The final issue is I want to change the background color of active tab to yellow as shown in image.Please help me fix this issue
try this
private void setupTabIcons() {
LayoutInflater inflater = LayoutInflater.from(this);
View view1 = inflater.inflate(R.layout.custom_view, null, false);
((TextView) view1.findViewById(R.id.text)).setText("Tab1");
((ImageView) view1.findViewById(R.id.image)).setImageResource(tabIcon[0]);
View view2 = inflater.inflate(R.layout.custom_view, null, false);
((TextView) view2.findViewById(R.id.text)).setText("Tab2");
((ImageView) view2.findViewById(R.id.image)).setImageResource(tabIcon[0]);
View view3 = inflater.inflate(R.layout.custom_view, null, false);
((TextView) view3.findViewById(R.id.text)).setText("Tab3");
((ImageView) view3.findViewById(R.id.image)).setImageResource(tabIcon[0]);
tabLayout.getTabAt(0).setCustomView(view1);
tabLayout.getTabAt(1).setCustomView(view2);
tabLayout.getTabAt(2).setCustomView(view3);
your custom view will look like
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
You can Use android:drawableLeft to display drawable on left of
textview properly.
For Different backgroundColor for Different state You can use
android:background for different color state like this
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;
}
}
}