Android Bottom Navigation bar 4 Items not showing properly on some devices - android

I got a little problem, as I'm trying to add 4 Icons to a Bottom Navigation Bar in Android.
On some devices it looks like this
But I want it to be looking like this
How to achieve that ? Thanks in advance
Don't know which code you need. Just added everything used by the viewpager for the Bottom navigation Bar
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_stdplan:
viewPager.setCurrentItem(0);
break;
case R.id.action_klausur:
viewPager.setCurrentItem(1);
break;
case R.id.action_hausaufgaben:
viewPager.setCurrentItem(2);
break;
case R.id.action_fehlzeiten:
viewPager.setCurrentItem(3);
break;
}
return false;
}
});
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (prevMenuItem != null) {
prevMenuItem.setChecked(false);
}
else
{
bottomNavigationView.getMenu().getItem(0).setChecked(false);
}
Log.d("page", "onPageSelected: "+position);
bottomNavigationView.getMenu().getItem(position).setChecked(true);
prevMenuItem = bottomNavigationView.getMenu().getItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
setupViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
stdplanFragment =new StdplanFragment();
klausurenFragment =new KlausurenFragment();
hausaufgabenFragment =new HausaufgabenFragment();
fehlzeitenFragment =new FehlzeitenFragment();
adapter.addFragment(stdplanFragment);
adapter.addFragment(klausurenFragment);
adapter.addFragment(hausaufgabenFragment);
adapter.addFragment(fehlzeitenFragment);
viewPager.setAdapter(adapter);
}
}
bottom_navigation.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_stdplan"
android:checked="true"
android:icon="#drawable/ic_dashboard_black_24dp"
android:title="#string/tab1"
app:showAsAction="never" />
<item
android:id="#+id/action_klausur"
android:checked="false"
android:icon="#android:drawable/ic_menu_agenda"
android:title="#string/tab2"
app:showAsAction="never" />
<item
android:id="#+id/action_hausaufgaben"
android:checked="false"
android:icon="#android:drawable/ic_menu_manage"
android:title="Hausaufgaben"
app:showAsAction="never" />
<item
android:id="#+id/action_fehlzeiten"
android:checked="false"
android:icon="#android:drawable/ic_menu_recent_history"
android:title="#string/tab3"
app:showAsAction="never" />
</menu>

I fixed it myself by changing the font size of the titles
Everyone else struggling with this: Just add these two lines to your dimens.xml
<dimen name="design_bottom_navigation_text_size" tools:override="true">10sp</dimen>
<dimen name="design_bottom_navigation_active_text_size" tools:override="true">10sp</dimen>

It could be a problem from a smallest thing possible. Not sure if it has anything to do with the image icons you have used, but can you please see if the image icons happen to have any paddings i.e. in the image itself?
Also for debugging purposes please remove the titles or keep them empty and see if it aligns the image icons properly.
Can you please change the following,
app:showAsAction="never"
to
app:showAsAction="ifRoom"
I would try following this link just in case.

Related

setOnMenuItemClickListener not working for Bottom App Bar when using app:actionLayout

I have used bottom app bar and the problem is when i used a custom layout for my menus using app:actionLayout in menu, the click is not working for these menus i.e setOnMenuItemClickListener for bottomappbar not working.?
It is working fine when actionLayout not used.
BottomAppBar bottomAppBar;
bottomAppBar = findViewById(R.id.bar);
bottomAppBar.replaceMenu(R.menu.announcement_menu);
bottomAppBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_all:
Log.d("Announcement", "All clicked");
break;
case R.id.action_rec:
Log.d("Announcement", "Received clicked");
break;
case R.id.action_sen:
Log.d("Announcement", "Sent clicked");
break;
}
return false;
}
});
And the menu file
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_all"
app:actionLayout="#layout/custom_menu_row_all"
android:title="All"
app:showAsAction="always" />
<item
android:id="#+id/action_rec"
app:actionLayout="#layout/custom_menu_row_received"
android:title="Received"
app:showAsAction="always" />
<item
android:id="#+id/action_sen"
app:actionLayout="#layout/custom_menu_row_sent"
android:title="Sent"
app:showAsAction="always" />
</menu>
Got working with following:
View v = bottomAppBar.getMenu().findItem(R.id.action_rec).getActionView().findViewById(R.id.tvTitle);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Announcement", "Received clicked");
}
});

Drawer layout with two navigation views and selected item colours

I have a drawer layout that needs to have two navigation views in it, because there's a couple of options that need to be aligned on top and another on the bottom, with a divider separating them.
I've managed to make it work, but now I have two different problems with my setup.
1) The first one, I can't change the selected items text color (the background color works as intented via a drawer selector, but for some reason, the selected item's text color is always colorPrimary)
2) The second one is trickier, since there's two navigation views, it can happen that there's a selected row on the first and on the second one, even though they all work loading fragments in the same container. Is there a way to manage that, when an item for the first navigation view is selected, the second navigation view's selected item gets deselected?
This is the drawer's layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- 1º Layout de la activity -->
<include layout="#layout/activity_main"/>
<!-- 2º Layout del drawer -->
<android.support.design.widget.NavigationView
android:id="#+id/container_navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:itemBackground="#drawable/drawer_list_selector"
android:nestedScrollingEnabled="true"
android:scrollIndicators="none">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:layout_width="match_parent"
android:layout_height="#dimen/divider_height"
android:background="#color/colorAccent"
android:layout_above="#+id/navigation_view"
android:id="#+id/top_separator"/>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:layout_above="#+id/bottom_separator"
app:itemBackground="#drawable/drawer_list_selector"
app:menu="#menu/menu_navigation" />
<View
android:layout_width="match_parent"
android:layout_height="#dimen/divider_height"
android:background="#color/colorAccent"
android:layout_above="#+id/navigation_bottom"
android:id="#+id/bottom_separator"/>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_bottom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:menu="#menu/menu_navigation_bottom"
app:itemBackground="#drawable/drawer_list_selector"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
This is the top navigation view's layout:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_tus_ofertas"
android:title="#string/tus_ofertas"
android:icon="#drawable/ic_offer" />
<item
android:id="#+id/nav_movimiento_puntos"
android:title="#string/movimiento_puntos"
android:icon="#drawable/ic_points"/>
<item
android:id="#+id/nav_asociaciones"
android:title="#string/asociaciones"
android:icon="#drawable/ic_flag"/>
</group>
</menu>
Bottom navigation view's layout:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_terminos"
android:title="#string/terminos"
android:icon="#drawable/ic_document" />
<item
android:id="#+id/nav_contacto"
android:title="#string/contacto"
android:icon="#drawable/ic_email"/>
<item
android:id="#+id/nav_valorar"
android:title="#string/valorar"
android:icon="#drawable/ic_rate_review"/>
<item
android:id="#+id/nav_exit"
android:title="#string/exit"
android:icon="#drawable/ic_shutdown"/>
</group>
</menu>
Selected item's background selector:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="#color/colorAccent" />
<item android:state_activated="true" android:drawable="#color/colorAccent" />
<item android:state_selected="true" android:drawable="#color/colorAccent" />
<item android:state_checked="true" android:drawable="#color/colorAccent" />
<item android:state_pressed="false" android:drawable="#android:color/transparent" />
<item android:state_activated="false" android:drawable="#android:color/transparent" />
<item android:state_selected="false" android:drawable="#android:color/transparent" />
<item android:state_checked="false" android:drawable="#android:color/transparent" />
</selector>
The activity that calls the drawer and handles the events:
public class MainActivity extends AppCompatActivity {
#Bind(R.id.toolbar) Toolbar toolbar;
#Bind(R.id.tabs) TabLayout tabs;
#Bind(R.id.drawer_layout) DrawerLayout drawerLayout;
#Bind(R.id.container_navigation) NavigationView containerNavigator;
#Bind(R.id.navigation_view) NavigationView navigationView;
#Bind(R.id.navigation_bottom) NavigationView navigationBottom;
#Bind(R.id.vsFooter) ViewStubCompat stub;
ImageView userPicture;
TextView userMail;
ViewPager viewPager;
Menu menu;
ActionBar actionBar;
ViewPagerFragment viewPagerFragment;
Usuario currentUser;
public Usuario getCurrentUser() {
return currentUser;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer);
ButterKnife.bind(this);
currentUser = UserApiManager.getInstance(getApplicationContext()).getCurrentUser();
viewPagerFragment = ViewPagerFragment.newInstance();
setupToolbar();
setupNavigationDrawer();
ApiManager.getInstance(getApplicationContext()).setupFooter(stub, currentUser.getIdLocalidad(), this);
getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout,viewPagerFragment).commit();
}
public void setupViewPager(ViewPager viewPager) {
tabs.setupWithViewPager(viewPager);
}
private void setupToolbar() {
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
if (actionBar!=null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_black);
actionBar.setTitle(getString(R.string.app_title));
}
}
private void setupNavigationDrawer() {
View headerView = navigationView.inflateHeaderView(R.layout.navigation_header);
userPicture = (ImageView) headerView.findViewById(R.id.user_picture);
userMail = (TextView) headerView.findViewById(R.id.user_mail);
userMail.setText(currentUser.getEmail());
Picasso.with(this).load(currentUser.getImagenURL()).transform(new CircleTransformation()).into(userPicture);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_tus_ofertas:
showTabLayout();
actionBar.setTitle(getString(R.string.app_title));
getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout,viewPagerFragment).commit();
break;
case R.id.nav_movimiento_puntos:
hideTabLayout();
Bundle bundle = new Bundle();
bundle.putString("idcliente", currentUser.getId());
MovimientoPuntosFragment movimientoPuntosFragment = MovimientoPuntosFragment.newInstance();
movimientoPuntosFragment.setArguments(bundle);
actionBar.setTitle(getString(R.string.movimiento_puntos));
getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, movimientoPuntosFragment).commit();
break;
case R.id.nav_asociaciones:
hideTabLayout();
actionBar.setTitle(getString(R.string.asociaciones));
getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, AsociacionFragment.newInstance()).commit();
break;
}
drawerLayout.closeDrawers();
return true;
}
});
navigationBottom.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_terminos:
hideTabLayout();
actionBar.setTitle(getString(R.string.terminos));
getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, LegalesFragment.newInstance()).commit();
break;
case R.id.nav_contacto:
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.parse("mailto:?subject=" + getString(R.string.contacto_email));
intent.setData(data);
startActivity(intent);
break;
case R.id.nav_valorar:
final String appPackageName = BuildConfig.APPLICATION_ID;
try {
Log.i("url", "market://details?id=" + appPackageName);
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
break;
case R.id.nav_exit:
break;
}
drawerLayout.closeDrawers();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_over, menu);
this.menu = menu;
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
break;
case R.id.action_user:
Intent intent = new Intent(this, PerfilUsuarioActivity.class);
startActivity(intent);
break;
}
return super.onOptionsItemSelected(item);
}
public void hideTabLayout(){
tabs.setVisibility(View.GONE);
}
public void showTabLayout(){
tabs.setVisibility(View.VISIBLE);
}
}
Any help would be appreciated!
Thanks in advance!
Solved!
The problem with the color I solved it with a selector, it didn't work before because I had a syntax error (selector tag inside the main selector tag).
This is the color selector's code:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#FFFFFFFF" android:state_checked="true" />
<item android:color="#E6000000" android:state_checked="false"/>
</selector>
The second problem I solved it by programmatically deselecting the other navigationview's items onNavigationItemSelected.
This is the function I call:
public void deselectItems(NavigationView view){
int size = view.getMenu().size();
for (int i = 0; i < size; i++) {
view.getMenu().getItem(i).setChecked(false);
}
}
I know there must be a better way to solve the second problem, but this one worked.

NavigationView slow to open / Skipping frames (Android Design Lib)

I'm using a NavigationView supplied by the Android Design Library. I've found after adding a few items to it that is performing quite poorly. On first launch it takes a second or so to open for the firs time. Here's a screenshot of the UI.
I'll try to post some of the relevant bits of code.
Drawer XML
<group android:checkableBehavior="single">
<item
android:id="#+id/home"
android:checked="false"
android:icon="#drawable/ic_home"
android:title="Home" />
<item
android:id="#+id/about"
android:checked="false"
android:icon="#drawable/ic_about"
android:title="About" />
<item
android:id="#+id/gallery"
android:checked="false"
android:icon="#drawable/ic_gallery"
android:title="Gallery" />
<item
android:id="#+id/settings"
android:icon="#drawable/ic_action_settings"
android:title="Settings" />
<item
android:id="#+id/navigation_subheader"
android:title="Categories">
<menu>
<item
android:id="#+id/science"
android:checked="false"
android:icon="#drawable/ic_science"
android:title="Science" />
<item
android:id="#+id/parenting"
android:checked="false"
android:icon="#drawable/ic_parenting"
android:title="Parenting" />
<item
android:id="#+id/android"
android:checked="false"
android:icon="#drawable/ic_android"
android:title="Android" />
<item
android:id="#+id/technology"
android:checked="false"
android:icon="#drawable/ic_tech"
android:title="Technology" />
<item
android:title=""
android:checkable="false"
android:visible="false"
android:orderInCategory="200"/>
</menu>
</item>
</group>
MainAct
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing Toolbar and setting it as the actionbar
toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
setSupportActionBar(toolbar);
//Initializing NavigationView
navigationView = (NavigationView) findViewById(R.id.navigation_view);
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not make it in checked state
if (menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
Log.v(TAG + "-S", "Pre_Switch = " + mCurCheckPosition);
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
case R.id.home:
homeFragment();
return true;
case R.id.about:
webFragment();
return true;
case R.id.gallery:
galleryFragment();
return true;
case R.id.science:
scienceFragment();
return true;
case R.id.parenting:
parentingFragment();
return true;
case R.id.android:
androidFragment();
return true;
case R.id.technology:
technologyFragment();
return true;
case R.id.settings:
Intent i = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(i);
default:
return true;
}
}
});
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.openDrawer, R.string.closeDrawer){
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawerLayout.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessay or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
And finally here is the error im seeing in the logs from the Choreographer, i'm hoping this is just a bug in the lib however im wondering if someone else came across this and might have a work around.
I/Choreographer﹕ Skipped 117 frames! The application may be doing too much work on its main thread.
Full source is available here: https://github.com/caman9119/The_Jones_Theory
Found the issue in my header.xml I was using a background.png that was 1080x720p. I scaled the image down to ~400x300 and voila, interesting problem indeed.
If you are using dynamic images for the background (using user facebook or g+ banner by example) and using Picasso this piece of code can be usefull:
ImageView background = (ImageView) findViewById(R.id.background);
Picasso
.with(context)
.load([Your image source here])
.fit()
.centerCrop()
.into(background)
Had the same problem, i was using 512 x 512 images in the drawer list. All images were initially placed in the 'drawable' folder but when i moved them to the 'drawable-xxhdpi' folder, it was butter smooth.

How to change Viewpager tab colour dynamically?

How to change colour of Tabs like this? When I click/swipe to green or any other tab, the tab colour should change to that appropriate colour and rest of other tabs colour should change to black. How can I do this? Im using Viewpager.
I tried this code inside onpagelistener:
if(position == 0) {
viewpager.getChildAt(position).setBackgroundColour(getResources().getcolor(R.color.red);
}
else if(position == 1) {
viewpager.getChildAt(position).setBackgroundColour(getResources().getcolor(R.color.green);
}
But above code has no effect.
And Im using this code : Android Viewpager tutorial Androidhive
Finally I solved it. Thanks to #Xcihnegn for his idea. This is the solution:
/* For setting default selected tab */
actionBar.setSelectedNavigationItem(0);
actionBar.getTabAt(0).setCustomView(R.layout.fragmnt_red);
/**
* 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);
if(position == 0)
{
actionBar.getSelectedTab().setCustomView(R.layout.fragmnt_red);
}else if(position == 1)
{
actionBar.getSelectedTab().setCustomView(R.layout.fragmnt_orange);
}else if(position == 2)
{
actionBar.getSelectedTab().setCustomView(R.layout.fragmnt_green);
}
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabSelected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction fragmentTransaction) {
viewPager.setCurrentItem(tab.getPosition());
}
When one tab gets unselected, setCustomView(null) changes its layout back to its original black colour. So only selected tabs will change colour. Unselecting the tabs will change its layout to original form.
#Override
public void onTabUnselected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction fragmentTransaction) {
if(tab.getPosition() == 0)
{
actionBar.getTabAt(0).setCustomView(null);
}else if(tab.getPosition() == 1)
{
actionBar.getTabAt(1).setCustomView(null);
}else if(tab.getPosition() == 2)
{
actionBar.getTabAt(2).setCustomView(null);
}
}
}
To remove unnecessary padding appear when setting the custom view we should use this code in styles.xml.
<style name="Custom.ActionBar.TabView.Empty" parent="#android:style/Widget.ActionBar.TabView">
<item name="android:paddingLeft">0dp</item>
<item name="android:paddingRight">0dp</item>
<item name="android:background">#000000</item>
</style>
<style name="CustomActionbartab" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="actionBarTabStyle">#style/Custom.ActionBar.TabView.Empty</item>
<item name="android:actionBarTabStyle">#style/Custom.ActionBar.TabView.Empty</item>
</style>
Dont forget to add the this code just above setcontentview in your activity.
settheme(R.styles.CustomActionbartab);
Custom layout for tabs.
<?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="#color/red">
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="RED"
android:textStyle="bold"
android:gravity="center"
android:textColor="#ffffff"/>
</RelativeLayout>
There is tutorial Styling tabs in the Android action bar. You can choose your parent theme as Theme.Holo for API>=3, or Theme.AppCompat for support library V7, etc.
And besides, for <item name="android:background">, you could set it to a selector you create for tab state change:
android:background="#drawable/selector_tab"
For selector_tab can be like:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#color/pressed_color"
android:state_pressed="true" />
<item android:color="#color/selected_color"
android:state_selected="true" />
<item android:color="#color/normal_color" />
</selector>
[UPDATE]
For change tab color dynamically, suggest to use custom view with tab:
//your_custom_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/tab_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:maxLines="1" />
</LinearLayout>
LinearLayout customView = (LinearLayout) getLayoutInflater().inflate(R.layout.your_custom_tab, null);
then setCustomeView(customView) when add tab to ActionBar. And in your tab/page change listener:
Tab selectedTab = yourActionBar.getSelectedTab();
View tabView = selectedTab.getCustomView();
tabView.setBackgroundColor(your_select_color);
To remove possible gap around tab caused by custom view, you can set tab style:
<style name="ActionBarTabStyle" parent="#android:style/Widget.AppCompat.Light.ActionBar.TabView">
<item name="android:paddingLeft">0dp</item>
<item name="android:paddingRight">0dp</item>
<item name="android:paddingTop">0dp</item>
<item name="android:paddingBottom">0dp</item>
</style>
and use your theme parent accordingly.
Hope this help!
I had a similar problem. In my case, I wanted to change the color of the action bar whenever the user clicked on one of the fragments in the navigation drawer.
Here is the code I used to resolve this issue.
Since you can't access the Action bar from a fragment, you have to create it in your main menu. Here is the method I used.
public void restoreActionBar(int parsedColor) {
this.parsedColor = parsedColor;
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
actionBar.setBackgroundDrawable(new ColorDrawable(parsedColor));
}
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main_activity_trekkly, menu);
restoreActionBar(parsedColor);
return true;
}
return super.onCreateOptionsMenu(menu);
}
Now in your class that extends fragment:
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivityTrekkly)activity).onSectionAttached(4);
MainActivityTrekkly mA = ((MainActivityTrekkly)getActivity());
mA.restoreActionBar(Color.parseColor("#028482"));
}
I got this working with the Navigation drawer so you might have to adapt this code.
Did this help?

How "onOptionsItemSelected" works for Fragments?

Menu Items getting disappeared in my app.
Initially i created menu items as follow. but menu getting disappeared in some android versions.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TabHelper tabHelper = getTabHelper();
CompatTab menuTab = tabHelper.newTab("menu").setText(
R.string.tab_section1).setIcon(R.drawable.home_icon).setTabListener(
new InstantiatingTabListener(this, MenuFragment.class));
tabHelper.addTab(menuTab);
CompatTab favTab = tabHelper.newTab("favourites").setText(
R.string.tab_section2).setIcon(R.drawable.favourites_icon).setTabListener(
new InstantiatingTabListener(this, FavouritesFragment.class));
tabHelper.addTab(favTab);
}
THIS ABOVE CODE WORKS FINE IN LATEST ANDROID 4.1.3 BUT FAILS TO DISPLAY IN 4.0.1 and 4.0.3
SEEMS TO BE SOME LAYOUT ISSUE.
TO RESOLVE i added menu xml as follow
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/menuhome"
android:icon="#drawable/map_icon"
android:title="#string/tab_section1"
android:orderInCategory="1"
android:showAsAction="always|withText" />
<item android:id="#+id/menumap"
android:icon="#drawable/map_icon"
android:title="#string/tab_section2"
android:orderInCategory="2"
android:showAsAction="always|withText" />
and added onOptionItemSelected as follow
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.menuhome:
finish();
return true;
case R.id.menumap:
//ERROR
//HOW CAN I CALL FRAGMENT HERE.?
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}

Categories

Resources