Custom tabs with TabLayout - android

I have a problem with implementing custom tabs, and I know i could've just used the setCompoundDrawablesWithIntrinsicBounds for just TextView in my Layout file, but I need to show 2 another ImageViews in one Layout file.I have a custom layout for it, which I inflate like this:
public class TabsAdapter extends FragmentPagerAdapter {
private int mPageCount;
private Context mContext;
private int[] stringResID = { R.string.serverString, R.string.localString, R.string.commonString, R.string.searchString };
private int[] imagesResID = { R.drawable.tab1, R.drawable.tab2, R.drawable.tab3, R.drawable.tab4};
public TabsAdapter(FragmentManager fm, int pageCount, Context context) {
super(fm);
mPageCount = pageCount;
mContext = context;
}
public View getTabView(int position) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_tab, null);
TextView tv = (TextView) view.findViewById(R.id.titleTab);
tv.setText(stringResID[position]);
ImageView img = (ImageView) view.findViewById(R.id.tabImage);
img.setImageDrawable(ContextCompat.getDrawable(mContext, imagesResID[position]));
return view;
}
#Override
public Fragment getItem(int position) {
return PageFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return mPageCount;
}
}
And my layout file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/titleTab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ololo"
android:layout_centerInParent="true"/>
<ImageView
android:id="#+id/tabImage"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerHorizontal="true"
android:layout_above="#+id/titleTab"/>
</RelativeLayout>
And call it from MainActivity like this:
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
TabsAdapter pagerAdapter =
new TabsAdapter(getSupportFragmentManager(), 4,MainActivity.this);
viewPager.setAdapter(pagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
if(tab != null) {
tab.setCustomView(pagerAdapter.getTabView(i));
}
}
So here's the question: what am I doing wrong? Becaus this code just gives me text in tabs, without ImageView. Please help if you tried to do something like this.

Related

show popup on long click on selected tab of tablayout

I'm creating an android application and I have an activity with a android.support.design.widget.TabLayout and a ViewPager in it .
here is my code
activity_main.xml
<android.support.percent.PercentRelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable" />
<android.support.v4.view.ViewPager
android:id="#+id/cards_grouping_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/tabs" />
MainActivity.java
public class MainActivity extends AppCompatActivity {
#BindView(R.id.tabs)
TabLayout tabs;
#BindView(R.id.cards_grouping_pager)
ViewPager pager;
private ArrayList<Category> categories = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_cards);
ButterKnife.bind(this);
categories = //getDataFromApi
doSomeWorks();
}
private void doSomeWorks() {
MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager(), categories);
pager.setAdapter(adapter);
tabs.setupWithViewPager(pager);
LinearLayout tabStrip = (LinearLayout) tabs.getChildAt(0);
for (int i = 0; i < tabStrip.getChildCount(); i++) {
final int finalI = i;
tabStrip.getChildAt(i).setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//I SHOULD SHOW POPUP HERE
}
});
}
}
public class MyPagerAdapter extends FragmentPagerAdapter {
private final ArrayList<String> TITLES = new ArrayList<>();
MyPagerAdapter(FragmentManager fm, ArrayList<Category> categories) {
super(fm);
for (int i = 0; i < categories.size(); i++) {
TITLES.add(categories.get(i).name);
}
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES.get(position);
}
#Override
public int getCount() {
return TITLES.size();
}
#Override
public Fragment getItem(int position) {
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
return HorizontalTabsAdapter.newInstance(position, categories, displayMetrics.widthPixels,
displayMetrics.heightPixels);
}
}
}
I want to when user long click on each tab a popup appear exactly in selected position .
like below picture
How can I do that?
(not enough credits to comment, so posting as answer)
To implement long press clicklistener on each tab of tablayout, follow these answers
https://stackoverflow.com/a/43522131/6387236
https://stackoverflow.com/a/34982710/6387236
For the implementation of Popup Window at the location of long press, follow this nice blog,
https://rajeshandroiddeveloper.blogspot.in/2013/07/android-popupwindow-example-in-listview.html
Hope this helps

How to set Custom tab in tab layout in android

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;
}

Android - tablayout with custom view tabs - drawable selector cannot be applied

I am trying to set up custom tabs in a tablayout using compile 'com.android.support:design:25.3.1' in gradle.
I want to use selectors so that when a tab is clicked it changes based on its state.
So I've tried the following unsuccessfully :
this is my activity xml:
<ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/white"/>
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"
style="#style/MyCustomTabLayout"
/>
here is the style i use for the tabLayout:
<style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
<item name="tabIndicatorColor">#android:color/transparent</item>
</style>
which hides the underline.
here is one of my selectors for my home tab:
here is the custom view i have for each tab:
<ImageView
android:id="#+id/iv_imgview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
tools:src="#drawable/home_tab_selector"
/>
<TextView
android:id="#+id/tv_tab_name"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="HOME"
/>
and here is the portion of code that creates the tablayout:
for (int i = 0; i < NUM_OF_TABS; i++)
tabLayout.addTab(tabLayout.newTab());
adapter = new LandingPagerAdapter(getApplicationContext(),getSupportFragmentManager(), tabLayout.getTabCount());
//Adding adapter to pager
viewPager.setAdapter(adapter);
tabLayout.addOnTabSelectedListener(this);
tabLayout.setupWithViewPager(viewPager);
// Iterate over all tabs and set the custom view
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(adapter.getTabView(i));
}
tabLayout.getTabAt(0).select();
and finally here is the getTabView method responsible for applying the selector and custom view:
public class LandingPagerAdapter extends FragmentStatePagerAdapter {
private final Context context;
//integer to count number of tabs
int tabCount;
private Fragment mCurrentFragment;
private String[] tabTitles = new String[]{"Home", "tab2"};
// configure tab icons
int[] imageTabResId = {
R.drawable.home_tab_selector,
R.drawable.tab_two_selector,;
//Constructor to the class
public LandingPagerAdapter(Context context, FragmentManager fm, int tabCount) {
super(fm);
this.context = context;
this.tabCount = tabCount;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
TabHomeContainerFragment tab1 = new TabHomeContainerFragment();
return tab1;
case 1:
TabTwoContainerFragment tab2 = new TabTwoContainerFragment();; //Todo: these should all be containers
return tab2;
default:
return null;
}
}
//Overriden method getCount to get the number of tabs
#Override
public int getCount() {
return tabCount;
}
public Fragment getCurrentFragment() {
return mCurrentFragment;
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
if (getCurrentFragment() != object) {
mCurrentFragment = ((Fragment) object);
}
super.setPrimaryItem(container, position, object);
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
public View getTabView(int position) {
// Given you have a custom layout in `res/layout/custom_tab.xml` with a TextView and ImageView
View v = LayoutInflater.from(context).inflate(R.layout.custom_landingpagetab, null);
TextView tv = (TextView) v.findViewById(R.id.tv_tab_name);
tv.setText(tabTitles[position]);
ImageView img = (ImageView) v.findViewById(R.id.iv_imgview);
img.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),imageTabResId[position]));
return v;
}
}
Notice in getTabView i am setting the image resource to be the selector in the array in the class field.
but nothing happens on the device on api 24 i have been testing on.
I'm using support library 27.1.1 and facing the same problem. After some research I found that the state_selected must be defined clearly. See code below:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/ic_chat_disabled" android:state_selected="false"/>
<item android:drawable="#drawable/ic_chat_enabled" android:state_selected="true"/>
</selector>
android:state_selected="false" is must have!
i ended up dropping the selector approach and just getting my customView from the tab. then i can change its view elements. i had a set of images in an array for selected and another for unselected.
then when the tabs switched i switch between the images based on tab position:
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
ImageView iv = (ImageView) tab.getCustomView().findViewById(R.id.iv_imgview);
TextView tv = (TextView) tab.getCustomView().findViewById(R.id.tv_tab_name);
iv.setImageDrawable(ContextCompat.getDrawable(this, imageTabResId_selected[tab.getPosition()]));
tv.setTextColor(ContextCompat.getColor(this, R.color.black));
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
ImageView iv = (ImageView) tab.getCustomView().findViewById(R.id.iv_imgview);
TextView tv = (TextView) tab.getCustomView().findViewById(R.id.tv_tab_name);
iv.setImageDrawable(ContextCompat.getDrawable(this, imageTabResId[tab.getPosition()]));
tv.setTextColor(ContextCompat.getColor(this, R.color.tabs_default_text));
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}

Dynamically replace fragment when using tablayout and viewpager in android

I have struggled in the past couple of days to find the solution to this problem:
I have one activity which contains a tab layout and a view pager. The view pager is filled with fragments using an adapter. Tabs are created with this viewpager and are fixed. My question is how can I change the layout of tabs dynamically (for example after a button click) ?
This is xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark" />
<android.support.design.widget.TabLayout
android:id="#+id/tablayout"
android:layout_width="match_parent"
android:layout_height="65dp"
android:background="#color/white"
app:tabMode="fixed"
app:tabGravity="fill"
android:theme="#style/ThemeOverlay.AppCompat.Dark" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
This is Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupToolbar();
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);
setupTabLayout(tabLayout);
}
private void setupToolbar(){
...
}
public void setupViewPager(ViewPager viewPager) {
pageAdapter = new FragmentPageAdapter(getApplicationContext(), getSupportFragmentManager());
pageAdapter.addFragment(ContentFragment.newInstance(), "Following", R.drawable.following);
pageAdapter.addFragment(ContentFragment.newInstance(), "Discover", R.drawable.flower);
pageAdapter.addFragment(ContentFragment.newInstance(), "", R.drawable.camera);
pageAdapter.addFragment(ProfileFragment.newInstance(), "Profile", R.drawable.profile);
pageAdapter.addFragment(ContentFragment.newInstance(), "Task List", R.drawable.list);
viewPager.setAdapter(pageAdapter);
}
public void setupTabLayout(TabLayout tabLayout) {
try {
tabLayout.setupWithViewPager(viewPager);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pageAdapter.getTabView(i));
}
tabLayout.requestFocus();
}
catch(Exception ex){
Log.e("errr2", ex.getMessage());
}
}
This is adapter:
public class FragmentPageAdapter extends FragmentStatePagerAdapter {
private Context mContext;
private List<Fragment> mFragments = new ArrayList<>();
private List<String> mFragmentTitles = new ArrayList<>();
private List<Integer> mFragmentIcons = new ArrayList<>();
public FragmentPageAdapter(Context context, FragmentManager fm) {
super(fm);
this.mContext = context;
}
public void addFragment(Fragment fragment, String title, int drawable) {
mFragments.add(fragment);
mFragmentTitles.add(title);
mFragmentIcons.add(drawable);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getItemPosition(Object object)
{
return POSITION_UNCHANGED;
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
public View getTabView(int position) {
View tab = LayoutInflater.from(mContext).inflate(R.layout.tabbar_view, null);
TextView tabText = (TextView) tab.findViewById(R.id.tabText);
ImageView tabImage = (ImageView) tab.findViewById(R.id.tabImage);
tabText.setText(mFragmentTitles.get(position));
tabImage.setBackgroundResource(mFragmentIcons.get(position));
if (position == 3) {
tab.setSelected(true);
}
return tab;
}
}
The normal way to replace a fragment is by calling
fragmentManager.beginTransaction().replace(placeholderId, editPrifileFragment).commit();
but what should I use for placeholderId in this case ? because in activity layout I don't have a placeholder for fragments, just a viewpager.
So how can I replace the fragment dynamically and also keep the back button functionality ?
I have searched a lot and found some hacky solutions , but I think this is a very common situation and should have a better solution.
thanks.
Your ViewPager Fragment should hold the placeholderId.
So in your Fragment (which is part of the ViewPager) you can call getChildFragmentManager() to add Fragment like you usually do.
childFragmentManager.beginTransaction().add(placeholderId, editPrifileFragment).addToBackStack(null).commit();

How to set icons and text in tabs instead of text only android

I've created a tab and trying to put icons and text in my tab layout but it always display text only. I tried displaying icons only as well but i'm having problem regarding getResource().getDrawable() and tried putting Context as well for the getDrawable() but i'm still having problem.
Here is my code for my ViewPagerAdapter
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[];
int NumbOfTabs;
Context mContext;
private int[] icons = {
R.drawable.abouttab,
R.drawable.programmetab,
R.drawable.speakerstab,
R.drawable.mapstab,
R.drawable.twittertab
};
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb, Context context) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
this.mContext = context;
}
#Override
public Fragment getItem(int position) {
if(position == 0)
{
Tab_About tab_about = new Tab_About();
return tab_about;
}
else if(position == 1)
{
Tab_one tab_one = new Tab_one();
return tab_one;
}else if(position == 2){
Tab_two tab_two = new Tab_two();
return tab_two;
}else if(position == 3){
Tab_three tab_three = new Tab_three();
return tab_three;
}else{
Tab_four tab_four = new Tab_four();
return tab_four;
}
}
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
// This method return the Number of tabs for the tabs Strip
#Override
public int getCount() {
return NumbOfTabs;
}
}
for the getPageTitle() function i also tried this code to display icons only but like i said above i'm having problem with getDrawable()
#Override
public CharSequence getPageTitle(int position) {
Drawable image = mContext.getResources().getDrawable(icons[position], null);
image.setBounds(0, 0, 48, 48);
SpannableString sb = new SpannableString(" ");
ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);
sb.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return sb;
}
In my MainActivity
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private ViewPager mPager;
private ViewPagerAdapter adapter;
private SlidingTabLayout mTabs;
private Context mContext;
CharSequence Titles[] = {"One", "Two", "Three", "Four", "Five"};
int Numboftabs = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setElevation(0);
adapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles, Numboftabs, mContext);
// Assigning ViewPager View and setting the adapter
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(adapter);
// Assigning the Sliding Tab Layout View
mTabs = (SlidingTabLayout) findViewById(R.id.tabs);
mTabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
mTabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsIndicator);
}
});
mTabs.setSelectedIndicatorColors(getResources().getColor(R.color.tabsIndicator));
mTabs.setViewPager(mPager);
}
can anyone help me? thank you so much...
Create a custom layout like below
<?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="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical" >
<ImageView
android:id="#+id/tabIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:paddingTop="2dp" />
<TextView
android:id="#+id/tabText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textColor="#FFFFFF" />
</LinearLayout>
Set custom layout to action bar tab
Tab tab = actionBar.newTab().setCustomView(R.layout.yourView)

Categories

Resources