I am trying to create a chat app for android based on chat21 sdk app on github, with chat21 demo app also in github and the thing is that I want to add Icons to TabLayouts and I am stuck there because I tried a couple times on my own and I just can't get it to work, so here is an image of how I want my chat tabs to look,
here is tab_activity.xml code:
<?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:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/windowBackground"
tools:context=".TabActivity">
<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.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:background="#color/colorPrimary"
android:layout_height="wrap_content"
app:tabIndicatorColor="#color/white"
app:tabIndicatorHeight="3dp" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>`
and here it is TabActivity in java:
package chat21.android.demo;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import org.chat21.android.core.ChatManager;
import org.chat21.android.ui.ChatUI;
import java.util.HashMap;
import java.util.Map;
public class TabActivity extends AppCompatActivity {
private static final String TAG = TabActivity.class.getName();
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.view_pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
ChatUI.getInstance().processRemoteNotification(getIntent());
}
#Override
protected void onResume() {
ChatManager.getInstance().getMyPresenceHandler().connect();
super.onResume();
}
#Override
protected void onDestroy() {
ChatManager.getInstance().getMyPresenceHandler().dispose();
super.onDestroy();
}
// #Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is
present.
// getMenuInflater().inflate(R.menu.menu_tab, menu);
// return true;
// }
//
// #Override
// public boolean onOptionsItemSelected(MenuItem item) {
// // Handle action bar item clicks here. The action bar will
// // automatically handle clicks on the Home/Up button, so long
// // as you specify a parent activity in AndroidManifest.xml.
// int id = item.getItemId();
//
// //noinspection SimplifiableIfStatement
// if (id == R.id.action_settings) {
// return true;
// }
//
// return super.onOptionsItemSelected(item);
// }
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private int tabsCount;
private Map<String, Item> tabsMap;
private String[] tabsTags;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
tabsMap = new HashMap<>();
// create a map with all tabs
tabsMap.put(getString(R.string.tag_home),
new Item(getString(R.string.tab_home_title), 1));
tabsMap.put(getString(R.string.tag_chat),
new Item(getString(R.string.tab_chat_title), 1));
tabsMap.put(getString(R.string.tag_profile),
new Item(getString(R.string.tab_profile_title), 1));
// retrieve tab tags
tabsTags = getResources().getStringArray(R.array.tab_tags);
tabsCount = tabsTags.length; // count tab tags
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
String tabTag = getTagByPosition(position);
if (tabTag.equals(getString(R.string.tag_home))) {
return HomeFragment.newInstance();
} else if (tabTag.equals(getString(R.string.tag_chat))) {
return ChatFragment.newInstance();
} else if (tabTag.equals(getString(R.string.tag_profile))) {
return UserProfileFragment.newInstance();
} else {
// default load home
return ChatFragment.newInstance();
}
}
#Override
public int getCount() {
return tabsCount;
}
private String getTagByPosition(int position) {
return tabsTags[position];
}
private String getTitleByTag(String tag) {
return tabsMap.get(tag).getTitle();
}
private int getIconByTag(String tag) {
return tabsMap.get(tag).getIcon();
}
#Override
public CharSequence getPageTitle(int position) {
String tabTag = getTagByPosition(position);
return getTitleByTag(tabTag);
}
private class Item {
private String title;
private int icon;
private Item(String title, int icon) {
setTitle(title);
setIcon(icon);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getIcon() {
return icon;
}
public void setIcon(int icon) {
this.icon = icon;
}
#Override
public String toString() {
return "Item{" +
"title='" + title + '\'' +
", icon='" + icon + '\'' +
'}';
}
}
}
}
I think you are looking for this:
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_tab_favourite,
R.drawable.ic_tab_call,
R.drawable.ic_tab_contacts
};
#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();
}
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 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<>();
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);
}
}
}
(this is the result)
This is the code which adds the Images:
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
}
and if you want the exact same like in your picture take a look at this page:
https://www.androidhive.info/2015/09/android-material-design-working-with-tabs/
at the point: 6. Custom Tab View with Icon & Text
Here is my code:
package demo.stackowerflow_demos;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.content.res.AppCompatResources;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TabLayout tab = findViewById(R.id.tab);
final ViewPager pager = findViewById(R.id.pager);
pager.setAdapter(new SectionsPagerAdapter(getSupportFragmentManager(), this));
setupTabWithViewPager(tab, pager, R.layout.tab_layout);
}
//tabs
enum Tab {
HOME(R.string.tab_home, R.drawable.ic_home),
CHAT(R.string.tab_chat, R.drawable.ic_chat),
PROFILE(R.string.tab_profile, R.drawable.ic_profile);
Tab(#StringRes int title,
#DrawableRes int icon) {
this.title = title;
this.icon = icon;
}
final #StringRes
int title;
final #DrawableRes
int icon;
static final Tab[] VALUES = values();
}
//simple interface
interface IconedTabPagerAdapter {
CharSequence getPageTitle(int position);
Drawable getPageIcon(int position);
}
//adapter for pager
static class SectionsPagerAdapter
extends FragmentPagerAdapter
implements IconedTabPagerAdapter {
private final Context mContext;
public SectionsPagerAdapter(FragmentManager fm,
Context context) {
super(fm);
mContext = context;
}
#Override
public Fragment getItem(int position) {
final Tab tab = Tab.VALUES[position];
switch (tab) {
case CHAT:
return ChatFragment.newInstance();
case PROFILE:
return UserProfileFragment.newInstance();
// default load home
case HOME:
default:
return HomeFragment.newInstance();
}
}
#Override
public int getCount() {
return Tab.VALUES.length;
}
#Override
public CharSequence getPageTitle(int position) {
final #StringRes int title = Tab.VALUES[position].title;
return mContext.getString(title);
}
#Override
public Drawable getPageIcon(int position) {
final #DrawableRes int icon = Tab.VALUES[position].icon;
return AppCompatResources.getDrawable(mContext, icon);
}
}
static void setupTabWithViewPager(#NonNull TabLayout tabLayout,
#NonNull ViewPager viewPager,
#LayoutRes int tabCustomView) {
final PagerAdapter adapter = viewPager.getAdapter();
if (!(adapter instanceof IconedTabPagerAdapter)) {
tabLayout.setupWithViewPager(viewPager);
return;
}
final IconedTabPagerAdapter iconedAdapter = ((IconedTabPagerAdapter) adapter);
for (int position = 0; position < adapter.getCount(); position++) {
final Drawable icon = iconedAdapter.getPageIcon(position);
final CharSequence title = adapter.getPageTitle(position);
tabLayout.addTab(tabLayout.newTab()
.setCustomView(tabCustomView)
.setIcon(icon)
.setText(title));
}
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
}
}
activity_main.xml
<?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="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabBackground="#color/tab_background"
app:tabIndicatorColor="#color/tab_indicator" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
tab_layout.xml
<?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">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:orientation="vertical">
<android.support.v7.widget.AppCompatImageView
android:id="#android:id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<android.support.v7.widget.AppCompatTextView
android:id="#android:id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAllCaps="true"
android:textColor="#color/tab_title_color" />
</LinearLayout>
</RelativeLayout>
Result:
Related
In my program, I have 2 implemented tabs using fragments. I've placed an EditText inside Tab2. I want to write all my main code for Tab2 inside onCreateView() of fragment Tab2, so that every time I swipe over to Tab2, this same code is executed. To test whether onCreateView() was being called every time I swiped to Tab2, I wrote the following statement in onCreateView() of Tab2:
text.setText("default");
Now when I run the app and swipe to Tab2- I see 'default' written. Now if I change this text manually, then swipe over to Tab1 and come back to Tab2- I still see this same text written. This obviously means that onCreateView() was not called again when I swiped to Tab2 for the 2nd time? How do I fix this?
Tab2.java
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Tab2 extends Fragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
setRetainInstance(false);
final View rootView;
rootView= inflater.inflate(R.layout.fragment_tab2, container, false);
text.setText("default");
return rootView;
}
}
MainActivity.java
package com.example.nirvan.diary30;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
{
public static int itemPosition;
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);
getSupportActionBar().setDisplayShowTitleEnabled(false);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
viewPager.setOffscreenPageLimit(0);
}
private void setupViewPager(ViewPager viewPager)
{
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new Tab1(), "ONE");
adapter.addFragment(new Tab2(), "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);
}
}
}
If you are using ViewPager
ViewPager viewPager;
Try to use setOnPageChangeListenerin MainActivity
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if(mFragmentList.size() > position && mFragmentList.get(position) instanceof Tab2)
{
((Tab2)mFragmentList.get(position)).changeText("changed text")
}
// you can use interface insted
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
in Tab2
public void changeText(String string){
text.setText(string);
}
Update MainActivity.java
public class MainActivity extends AppCompatActivity
{
public static int itemPosition;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
ViewPagerAdapter adapter;
private final List<Fragment> mFragmentLists = new ArrayList<>();
#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);
getSupportActionBar().setDisplayShowTitleEnabled(false);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
viewPager.setOffscreenPageLimit(0);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if(mFragmentList.size() > position && mFragmentList.get(position) instanceof Tab2)
{
((Tab2)mFragmentList.get(position)).changeText("changed text")
}
// you can use interface insted
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
private void setupViewPager(ViewPager viewPager)
{
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new Tab1(), "ONE");
adapter.addFragment(new Tab2(), "TWO");
viewPager.setAdapter(adapter);
mFragmentLists = adapter.getFragements();
}
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 List<Fragment> getFragements()
{
return mFragmentList;
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
I am trying to show icons in my tab, I am using tablayout and viewpager , but when I m calling tablayout.setupWithViewPager(viewpager) my icons are disappearing
Min sdk is 16
Target is 24
Support library 24.2.1
this is how I am setting my Tabs :-
private void setUpTabs(){
tabs.setupWithViewPager(viewpager);
TabLayout.Tab discoverTab = tabs.newTab();
TabLayout.Tab placesTab = tabs.newTab();
TabLayout.Tab rewardTab = tabs.newTab();
Drawable discover = ContextCompat.getDrawable(this, R.drawable.discover);
discover.setAlpha(255);
discover.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
Drawable places = ContextCompat.getDrawable(this, R.drawable.places);
places.setAlpha(55);
places.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
Drawable rewards = ContextCompat.getDrawable(this, R.drawable.rewards);
rewards.setAlpha(55);
rewards.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
discoverTab.setIcon(discover);
placesTab.setIcon(places);
rewardTab.setIcon(rewards);
tabs.addTab(discoverTab,0);
tabs.addTab(placesTab,1);
tabs.addTab(rewardTab,2);
}
ViewPager :-
private void setUpViewPager(){
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(DiscoverFragment.getFragment(null),"Discover");
adapter.addFrag(PlacesFragment.getFragment(null),"Places");
adapter.addFrag(RewardsFragment.getFragment(null),"Rewards");
viewpager.setAdapter(adapter);
}
ViewPagerAdapter :-
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
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 null to display only the icon
return null;
}
}
my XML layout :-
<?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:id="#+id/main_content"
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/action_bar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll"
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/colorPrimary"
app:tabGravity="fill"
app:tabIndicatorColor="#android:color/white"
app:tabMode="fixed"
app:tabSelectedTextColor="?attr/colorAccent"
app:tabTextColor="#android:color/black" />
</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>
Just try this way it will work for you
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_tab_favourite,
R.drawable.ic_tab_call,
R.drawable.ic_tab_contacts
};
#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();
}
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 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<>();
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);
}
}
}
For more check Tablayout
I want to set image/icon in Tabsin the following code:
in my application i set Tabs in Bottom and now i want to set image in the space of the text.. i tried tutorials also but not getting output as i wanted to
Here Tab.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
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/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/orange"
/>
</LinearLayout>
Now Tab.Java
package com.example.sachin.navigationwithswipe;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TabHost;
public class TabFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 3 ;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View x = inflater.inflate(R.layout.tab_layout,null);
tabLayout = (TabLayout) x.findViewById(R.id.sliding_tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
/**
* Return fragment with respect to Position .
*/
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new PrimaryFragment();
case 1 : return new SocialFragment();
case 2 : return new UpdatesFragment();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
/**
* This method returns the title of the tab according to the position.
*/
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "Primary";
case 1 :
return "Social";
case 2 :
return "Updates";
}
return null;
}
}
}
i want to set Image in the Tabs using following code.
Use this to set icon in tab
tabLayout.setupWithViewPager(viewPager);
//You tab icons
private int[] icons = {
R.drawable.one,
R.drawable.two,
R.drawable.three
};
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setIcon(icons[i]);
}
Also If you want only Icon then on Adapter pass pageTitle null
#Override
public CharSequence getPageTitle(int position) {
// return null to display only the icon
return null;
}
Use this for Selector. This Might Work
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/icon_on" android:state_selected="true"/>
<item android:drawable="#drawable/icon_off"/> <!-- default -->
</selector>
Set icon like this way..
mTabLayout.addTab(mTabLayout.newTab().setIcon(R.drawable.yourIcon));
To set both icon and text:
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_tab_favourite,
R.drawable.ic_tab_call,
R.drawable.ic_tab_contacts
};
#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();
}
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 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<>();
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);
}
}
}
Setting only icon to tab is same as setting text and icon except the method getPageTitle() in ViewPagerAdapter class returns null instead of tab label.
Modify MainActivity.java and modify the getPageTitle() method as :
#Override
public CharSequence getPageTitle(int position) {
// return null to display only the icon
return null;
}
i am working on android app which contains five tabs. Every tabs need to multiple pages and on tab re select, it should go on First fragment of every tabs. Below is my code;
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.icon_discover));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.icon_my_cuddll));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.helpicon_feedback));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.icon_notifications));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.icon_user));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdaptor adapter = new PagerAdaptor
(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());
tab.getIcon().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN);
if(tab.getPosition()==4)
{
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
tab.getIcon().setColorFilter(Color.parseColor("#87243D"), PorterDuff.Mode.SRC_IN);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
My pager adapter class is as follows:
public class PagerAdaptor extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdaptor(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
CuddllFragment tab1 = new CuddllFragment ();
return tab1;
case 1:
MyCuddllFragment tab2 = new MyCuddllFragment();
return tab2;
case 2:
// CuddllConversationFragment tab3 = new CuddllConversationFragment();
ConversationFragment conversationFragment = new ConversationFragment();
return conversationFragment;
case 3:
// CuddllNotificationsFragment tab4 = new CuddllNotificationsFragment();
Tab4ContainerFragment notificationPageFragment = new Tab4ContainerFragment();
return notificationPageFragment;
case 4:
MyProfileFragment tab5 = new MyProfileFragment();
return tab5;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
Tab.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TabFragment"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
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/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/orange" />
</LinearLayout>
Here TabFragment.Java
package com.example.sachin.omcommunication;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TabFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 3 ;
private int[] tabIcons = {
R.drawable.tab_home,
R.drawable.arrow,
R.drawable.tab_home
};
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View x = inflater.inflate(R.layout.activity_home_page,null);
tabLayout = (TabLayout) x.findViewById(R.id.sliding_tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
//You tab icons
int[] icons = {
R.drawable.tab_home,
R.drawable.arrow,
R.drawable.tab_home
};
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setIcon(icons[i]);
}
}
});
tabLayout.setupWithViewPager(viewPager);
return x;
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
/**
* Return fragment with respect to Position .
*/
#Override
public android.support.v4.app.Fragment getItem(int position)
{
switch (position){
case 0 : return new HomePage();
case 1 : return new Attendence();
case 2 : return new Delivery();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
/**
* This method returns the title of the tab according to the position.
*/
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "Primary";
case 1 :
return "Social";
case 2 :
return "Updates";
}
return null;
}
}
}
Try this.. might be work for you.
How can I add Tabs & Fragment dynamically ?
My code :
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
for (int i = 0; i < 4; i++) {
adapter.addFrag(new TabFragment(), "Tab"+i);
}
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Tab Fragment
public class TabFragment extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activty_listview,container, false);
listView = (ListView) rootView.findViewById(android.R.id.list);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
Suppose my tab names are "Tab1, Tab2, Tab3"
How can I add tabs dynamically according to the Array if I get above and how to tab fragment know which tab selected.
Any suggestions are welcomed.
Thanks in advance:)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="fill_parent"
app:tabMode="fixed"
android:background="#ff0000"
app:tabGravity="fill"
android:layout_height="48dp" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_below="#+id/sliding_tabs"
android:background="#android:color/white" />
</RelativeLayout>
Activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
int icons[] = {R.mipmap.createuser, R.mipmap.ico_password, R.mipmap.gplus, R.mipmap.fb};
int colors[] = {Color.YELLOW, Color.CYAN, Color.LTGRAY, Color.CYAN};
void initViews() {
TabLayout tabs = (TabLayout) findViewById(R.id.sliding_tabs);
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
LayoutInflater inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ArrayList<Fragment> fragments = new ArrayList<>(Arrays.asList(new Fragment1(),new Fragment2(),new Fragment3(),new Fragment4()));
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager(),fragments);
pager.setAdapter(adapter);
tabs.setupWithViewPager(pager);
for (int i = 0; i < 4; i++) {
View view = inflator.inflate(R.layout.tabs,null,false);
TextView title = (TextView)view.findViewById(R.id.title);
RelativeLayout layout = (RelativeLayout)view.findViewById(R.id.layout);
ImageView icon = (ImageView)view.findViewById(R.id.icon);
title.setText("Tab" + i);
layout.setBackgroundColor(colors[i]);
icon.setImageResource(icons[i]);
// tabs.getTabAt(i).setCustomView(view);
tabs.getTabAt(i).setIcon(icons[i]);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Adapter:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.List;
/**
* Created by rohit.h on 12/21/2015.
*/
public class ViewPagerAdapter extends FragmentPagerAdapter {
String titles[] = {"Tab1", "Tab2", "Tab3", "Tab4"};
private final List<Fragment> fragments;
public ViewPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
mTabLayout = (TabLayout)rootView.findViewById(R.id.tab_layout);
mTabLayout.addTab(mTabLayout.newTab().setText(getResources().getString(R.string.tab1)));
mTabLayout.addTab(mTabLayout.newTab().setText(getResources().getString(R.string.tab2)));
mTabLayout.addTab(mTabLayout.newTab().setText(getResources().getString(R.string.tab3)));
mTabLayout.addTab(mTabLayout.newTab().setText(getResources().getString(R.string.tab4)));
mTabLayout.addTab(mTabLayout.newTab().setText(getResources().getString(R.string.tab5)));
mTabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
mViewPager = (ViewPager)rootView.findViewById(R.id.pager);
mPagerAdapter = new PagerAdapter
(getActivity().getSupportFragmentManager(), mTabLayout.getTabCount());
mViewPager.setAdapter(mPagerAdapter);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
you can refer this link
A simple solution (but not the best/perfect one) would be to add the fragments to adapter and set the tablayout and adapter to viewpager again at runtime. Will not be clean / might be jerky but will definitely work.
EDIT::
There's a method in FragmentPagerAdapter which is set to viewpager and tablayout as well : notifyDataSetChanged(). Use this method after inserting and removing fragments from pager adapter. I tried this for inserting it works. Should definitely work for removing as well.