How can I add a badge to tab ? I am using this code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
main activity.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</android.support.v4.view.ViewPager>
</FrameLayout>
Tabs adapter java
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new RandomsFragment();
case 1:
return new ChatsFragment();
}
return null;
}
#Override
public int getCount() {
return 2;
}
}
I am following this tutorial for tabs:http://www.androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/
I didn't understand how can I add a badge to tabs.
first step is creating custom layout for each tabs so:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="center_vertical"
android:paddingLeft="6dip"
android:minHeight="?android:attr/listPreferredItemHeight"
/>
then when you want to add tabs to actionbar you must do :
private void addTabs(ActionBar actionBar)
{
ActionBar.Tab tab1=actionBar.newTab();
tab1.setTabListener(this);
tab1.setCustomView(R.layout.tab);
TextView txt1 = (TextView)tab1.getCustomView().findViewById(R.id.text1);
txt1.setText("Tab 1");
ActionBar.Tab tab2=actionBar.newTab();
tab2.setTabListener(this);
tab2.setCustomView(R.layout.tab);
TextView txt2 = (TextView)tab2.getCustomView().findViewById(R.id.text1);
txt2.setText("Tab 2");
ActionBar.Tab tab3=actionBar.newTab();
tab3.setCustomView(R.layout.tab);
tab3.setTabListener(this);
TextView txt3 = (TextView)tab3.getCustomView().findViewById(R.id.text1);
txt3.setText("Tab 3");
actionBar.addTab(tab1);
actionBar.addTab(tab2);
actionBar.addTab(tab3);
}
so in order to access them and add badgeView :
View v = getActionBar().getTabAt(0).getCustomView();
BadgeView badge = new BadgeView(getActivity(), v);
badge.setText("1");
badge.show();
the result will be:
After tweaking around with a few other solutions I came up with something simple and hope this would help someone.
create a custom tab layout tab_badge.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"
android:background="#android:color/transparent">
<TextView
android:id="#+id/tab_badge"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="#drawable/badge_background"
android:gravity="center"
android:layout_centerVertical="true"
android:textColor="#color/colorWhite"
android:textSize="20sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/tab_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="16sp"
android:textColor="#color/colorWhite"
android:text="test"
android:textStyle="bold"
android:gravity="center"
android:textAppearance="#style/Widget.AppCompat.Light.ActionBar.TabText"
android:layout_toRightOf="#+id/tab_badge"/>
</RelativeLayout>
badge_background.xml is an oval drawable filled with the color you want for the badge
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
<solid android:color="#color/colormaterialred500" />
</shape>
Extend textview to get myBadgeView class:
public class myBadgeView extends TextView {
private View target;
public myBadgeView(Context context, View target) {
super(context);
init(context, target);
}
private void init(Context context, View target) {
this.target = target;
}
public void updateTabBadge(int badgeNumber) {
if (badgeNumber > 0) {
target.setVisibility(View.VISIBLE);
((TextView) target).setText(Integer.toString(badgeNumber));
}
else {
target.setVisibility(View.GONE);
}
}
}
In your activity declare the tablayout as follows:
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
TabLayout.Tab tab1 = tabLayout.newTab();
tab1.setCustomView(R.layout.tab_badge);
TextView tab_text_1 = (TextView) tab1.getCustomView().findViewById(R.id.tab_text);
tab_text_1.setText("Tab1");
tabLayout.addTab(tab1);
badge1 = new myBadgeView(this, tab1.getCustomView().findViewById(R.id.tab_badge)); tab1.getCustomView().findViewById(R.id.tab_badge);
//set the badge for the tab
badge1.updateTabBadge(badge_value_1);
AFAIK, badge is not supported out of the box. You may find this library helpful: https://github.com/jgilfelt/android-viewbadger
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'm try using custom_tab_layout to implement badgeView but the icon in tab is not changing again when the tab is selected. Before i use custom_tablayout, icon in tab is change from grey to white when the tab is selected. Is there something i missed, this is the java file
public class MainActivity extends BaseActivity implements IMainView, TabLayout.OnTabSelectedListener {
private TabLayout tlMain;
private ViewPager vpMain;
private PagerAdapter pagerAdapter;
private MainPresenter mainPresenter;
private int[] tabIcons = {R.mipmap.ic_feeds_shade, R.mipmap.ic_notifications_shade
,R.mipmap.ic_sms_shade, R.mipmap.ic_event_note_shade
,R.mipmap.ic_account_circle_copy};
private int[] tabIconsWhite = {R.mipmap.ic_feeds_putih, R.mipmap.ic_notifications_putih
,R.mipmap.ic_sms_putih, R.mipmap.ic_event_note_putih
,R.mipmap.ic_account_circle_putih};
private String[] title = {"Laporan","Pemberitahuan","Perpesanan"
,"Agenda","Profile"};
private int[] unread = {0,7,0,0,0};
private Toolbar toolbar;
private ImageView iconTabItem;
private TextView badgeView;
public static void start(Context context){
Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra("isLogin", true);
context.startActivity(intent);
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_main);
mainPresenter = new MainPresenter(this);
mainPresenter.onCreate(context);
}
private void goToLogin(){
LoginActivity.start(context);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
vpMain.setCurrentItem(tab.getPosition());
tab.setIcon(tabIconsWhite[tab.getPosition()]);
switch (tab.getPosition()){
case 0:
vpMain.setCurrentItem(0);
toolbar.setTitle(title[0]);
break;
case 1:
vpMain.setCurrentItem(1);
toolbar.setTitle(title[1]);
break;
case 2:
vpMain.setCurrentItem(2);
toolbar.setTitle(title[2]);
break;
case 3:
vpMain.setCurrentItem(3);
toolbar.setTitle(title[3]);
break;
case 4:
vpMain.setCurrentItem(4);
toolbar.setTitle(title[4]);
break;
default:
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
tab.setIcon(tabIcons[tab.getPosition()]);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
#Override
public void initView() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(title[0]);
tlMain = (TabLayout) findViewById(R.id.tl_main);
tlMain.setupWithViewPager(vpMain);
tlMain.addTab(tlMain.newTab());
tlMain.addTab(tlMain.newTab());
tlMain.addTab(tlMain.newTab());
tlMain.addTab(tlMain.newTab());
tlMain.addTab(tlMain.newTab());
tlMain.setTabGravity(TabLayout.GRAVITY_FILL);
tlMain.setOnTabSelectedListener(this);
pagerAdapter = new PagerAdapter(getSupportFragmentManager(), tlMain.getTabCount());
vpMain = (ViewPager) findViewById(R.id.vp_main);
vpMain.setAdapter(pagerAdapter);
vpMain.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tlMain));
if(getIntent().getExtras() != null){
Bundle bundle = getIntent().getExtras();
if(!bundle.getBoolean("isLogin")){
goToLogin();
}
}else{
goToLogin();
}
try {
for (int i = 0; i < 6; i++){
tlMain.getTabAt(i).setCustomView(prepareTabView(i));
}
} catch (Exception e){
e.printStackTrace();
}
}
public View prepareTabView(int pos){
View view = getLayoutInflater().inflate(R.layout.custom_tablayout, null);
iconTabItem = (ImageView)view.findViewById(R.id.icon_tabitem);
badgeView = (TextView)view.findViewById(R.id.tab_count);
iconTabItem.setImageResource(tabIcons[pos]);
if (unread[pos]>0){
badgeView.setVisibility(View.VISIBLE);
badgeView.setText(String.format(Locale.getDefault(), "%d", unread[pos]));
} else
badgeView.setVisibility(View.GONE);
return view;
} }
this is view_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:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include layout="#layout/dc_toolbar" />
<android.support.design.widget.TabLayout
android:id="#+id/tl_main"
android:layout_width="match_parent"
android:layout_height="65dp"
android:background="#color/colorPrimaryDark"
app:tabIndicatorColor="#color/dc_white"
app:tabIndicatorHeight="4dp"
app:tabSelectedTextColor="#color/dc_yellow"
app:tabTextAppearance="#android:style/TextAppearance.Widget.TabWidget"
app:tabTextColor="#color/dc_white" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/vp_main"
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 for custom_tablayout.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="wrap_content">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/icon_tabitem"
android:src="#mipmap/ic_notifications_shade" />
<TextView
android:id="#+id/tab_count"
android:layout_width="12dp"
android:layout_height="12dp"
android:background="#drawable/badge_item_count"
android:gravity="center"
android:text="99"
android:padding="1dp"
android:textColor="#color/dc_white"
android:textSize="6sp"
android:textStyle="bold"
android:layout_alignEnd="#+id/icon_tabitem"/>
</RelativeLayout>
</RelativeLayout>
thank you for the help :)
You can use below code snippet.
private void updateTabIcon() {
mTabLayout.setupWithViewPager("your_pager");
for (int pos = 0; pos < "your_total_tab_count"; pos++) {
TabLayout.Tab tab = mTabLayout.getTabAt(pos);
assert tab != null;
tab.setCustomView(R.layout."your_custom_tab_view");
ImageView tabIcon = (ImageView) tab.getCustomView().findViewById(R.id.icon);
TextView badgeView = (TextView) tab.getCustomView().findViewById(R.id.text1);
//Use switch or if to set particular icon to particular tab
badgeView.setText("your_badge_Text");
tabIcon.setImageResource("your_selector_icon_drawable");
}
}
Note: Use selector for drawable selected and unselected.
Ex: icon_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/"selected_drawable" android:state_selected="true" />
<item android:drawable="#drawable/"unselected_drawable" android:state_selected="false" />
</selector>
You could try to create a function which changes all the icons back to the default and then call it before assigning the selected icon in onTabSelected :)
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
i'm trying to get this pageviewer with fragments to work however i'm stumbled on a problem where the view stays on screen on swipe. Ideally, i'd want it to only be on a particular layout yet i'm not too sure why it "carries over" to other screens (it also stays on screen during the transition between fragments).
Any feedback will be appreciated!
Link to Imgur Screenshots
Main:
private void initUI()
{
// ---------Page Viewer with Fragments -----------
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getSupportActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
}
Adapter:
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Main Frag
return new Fragment1();
case 1:
// Second Frag
return new Fragment2();
case 2:
// Third Frag
return new Fragment3();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
Fragment classes are basically this:
public class Fragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main, container, false);
return rootView;
}
}
Main Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
The EditText is in the main layout, the same layout that the ViewPager is in. It should be inflated within the tab. You'll need to create a separate layout for each tab.
Main layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
layout_fragment_1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
Then you need to inflate the new layout in fragment 1.
View rootView = inflater.inflate(R.layout.layout_fragment_1, container, false);
return rootView;
I would like to make it possible to swipe between the tabs in my app.
I have already found plenty tutorials to do this, but I can't get it to work with my code, because I use different code.
MyActivity.class:
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tabA = actionBar.newTab();
tabA.setIcon(R.drawable.icon_settings);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
tabA.setText("");
tabA.setTabListener(new com.example.MainActivity.TabListener<Tab1>(this, "Tab1", Tab1.class));
actionBar.addTab(tabA);
Tab tabB = actionBar.newTab();
tabB.setText("Tab2");
tabB.setTabListener(new com.example.MainActivity.TabListener<Tab2>(this, "Tab2", Tab2.class));
actionBar.addTab(tabB);
Tab tabC = actionBar.newTab();
tabC.setText("Tab3");
tabC.setTabListener(new com.example.MainActivity.TabListener<Tab3>(this, "Tab3", Tab3.class));
actionBar.addTab(tabC);
if (savedInstanceState != null) {
int savedIndex = savedInstanceState.getInt("SAVED_INDEX");
getActionBar().setSelectedNavigationItem(savedIndex);
}
}
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TabHost
android:id="#+id/tabHost"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:paddingTop="5dip">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TabWidget>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="#+id/einstellungen"
android:layout_width="fill_parent"
android:layout_height="wrap_content" android:orientation="vertical" android:background="#ffffff">
</LinearLayout>
<LinearLayout
android:id="#+id/tab1"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</LinearLayout>
<LinearLayout
android:id="#+id/tab2"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</LinearLayout>
<LinearLayout
android:id="#+id/tab3"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
Tab1.class
public class Tab1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.fragment_a, container, false);
return myFragmentView;
}
}
TabListener.class
public class TabListener <T extends Fragment> implements ActionBar.TabListener{
private final Activity myActivity;
private final String myTag;
private final Class myClass;
public TabListener(Activity activity, String tag, Class<T> cls) {
myActivity = activity;
myTag = tag;
myClass = cls;
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
Fragment myFragment = myActivity.getFragmentManager().findFragmentByTag(myTag);
if (myFragment == null) {
myFragment = Fragment.instantiate(myActivity, myClass.getName());
ft.add(android.R.id.content, myFragment, myTag);
} else {
ft.attach(myFragment);
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
Fragment myFragment = myActivity.getFragmentManager().findFragmentByTag(myTag);
if (myFragment != null) {
ft.detach(myFragment);
}
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
You can do it easier using the default ActionBar Tabs + Swipe Views of your Eclipse, Android Sudio or IntelliJ IDEA. Anyway you can take a look at my answer here Android ActionBar Tabs - Swipe or here Creating Swipe Views with Tabs you can find a very nice tutorial by Android Developers.
Hope I helped you