ActionBar title is not visible - android

I have implemented an actionbar but its title is not getting displayed. Also my app has two fragments , the title should change as per the fragment displayed.
public class MainActivity extends FragmentActivity {
/** Called when the activity is first created. */
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setupActionBar();
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new OnPageChangeListener()
{
public void onPageSelected(int position)
{
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
}
public void onPageScrollStateChanged(int state)
{
if (state == ViewPager.SCROLL_STATE_DRAGGING)
{
}
if (state == ViewPager.SCROLL_STATE_IDLE)
{
}
}
});
}
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
return new AllPatient();
case 1:
//Intent intent = new Intent(MainActivity.this,abc.class);
return new LaunchpadSectionFragment();
}
return null;
}
#Override
public int getCount() {
return 2;
}
}
private void setupActionBar() {
ActionBar actionBar = getActionBar();
//actionBar.setDisplayShowHomeEnabled(false);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM,
ActionBar.DISPLAY_SHOW_CUSTOM);
ViewGroup v = (ViewGroup)LayoutInflater.from(this)
.inflate(R.layout.header, null);
actionBar.setCustomView(v,
new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,
ActionBar.LayoutParams.WRAP_CONTENT,
Gravity.CENTER_VERTICAL | Gravity.RIGHT));
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(getTitle());
}
}
Please also tell me how to add dividers between the icons in actionbar.
Thanks in advance.

Try changing this line:
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM, ActionBar.DISPLAY_SHOW_CUSTOM);
By this one:
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME, ActionBar.DISPLAY_SHOW_CUSTOM);

Add the show title flag like so
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_SHOW_CUSTOM, ActionBar.DISPLAY_SHOW_CUSTOM);

I think the problem is that you're adding a custom view with a width of MATCH_PARENT and Android removes the action bar title (but not the home icon) in that case. It's not very logical, but that's the behavior I see in my app. Setting the width to WRAP_CONTENT creates the same problem. The solution is to give the custom view a fixed width, or if you need the width to vary from one activity to another, calculate the width programmatically and set it to a new fixed width for each activity.

This should definitely work
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setTitle(title);

Related

Android tablayout tabs with viewpager in toolbar in landscape

I have a tab layout and a view pager. In portrait mode I want tabs to appear below toolbar but in landscape mode I want tabs to appear in toolbar like this screenshot:
What I want
What I have
There are two tabs Recorder and Player. Before it was fine but after I added landscape layout it became like this.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
ArrayList<String> filenamesarraylist;
ArrayList<String> arrPackage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, FileObserverService.class);
startService(intent);
// Standard tabbed navigation setup.
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// ...
// Create tabs, fragments, pager and anything else needed.
// ...
//toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
forceTabs(); // Force tabs when activity starts.
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
viewPager.getAdapter().notifyDataSetChanged();
if (position == 0) {
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#Override
public void onConfigurationChanged(final Configuration config) {
super.onConfigurationChanged(config);
forceTabs(); // Handle orientation changes.
}
// This is where the magic happens!
public void forceTabs() {
try {
final ActionBar actionBar = getActionBar();
final Method setHasEmbeddedTabsMethod = actionBar.getClass()
.getDeclaredMethod("setHasEmbeddedTabs", boolean.class);
setHasEmbeddedTabsMethod.setAccessible(true);
setHasEmbeddedTabsMethod.invoke(actionBar, true);
}
catch(final Exception e) {
// Handle issues as needed: log, warn user, fallback etc
// This error is safe to ignore, standard tabs will appear.
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu1, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.settings:
Intent i = new Intent(getApplicationContext(), SettingsActivity.class);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new RecordFragment(), "RECORDER");
adapter.addFragment(new ListenFragment(), "PLAYER");
viewPager.setAdapter(adapter);
}
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 addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
#Override
public int getItemPosition(Object object) {
// POSITION_NONE makes it possible to reload the PagerAdapter
return POSITION_NONE;
}
}
}
Theme:
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
try this code:
public class MainActivity extends Activity {
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.awesome_tabbed_layout);
// Standard tabbed navigation setup.
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// ...
// Create tabs, fragments, pager and anything else needed.
// ...
forceTabs(); // Force tabs when activity starts.
}
#Override
public void onConfigurationChanged(final Configuration config) {
super.onConfigurationChanged(config);
forceTabs(); // Handle orientation changes.
}
// This is where the magic happens!
public void forceTabs() {
try {
final ActionBar actionBar = getActionBar();
final Method setHasEmbeddedTabsMethod = actionBar.getClass()
.getDeclaredMethod("setHasEmbeddedTabs", boolean.class);
setHasEmbeddedTabsMethod.setAccessible(true);
setHasEmbeddedTabsMethod.invoke(actionBar, true);
}
catch(final Exception e) {
// Handle issues as needed: log, warn user, fallback etc
// This error is safe to ignore, standard tabs will appear.
}
}
}
output:
portrait mode:
Landscape mode:

onTabSelected change Fragment

I am trying to change the Fragment onTabSelected.
Because at the moment, if you swipe the transitions work fine. But if you click on the Tab, the Fragments won't switch. The Tab gets highlighted, but the content remains the same.
The issue is with my onTabSelected method. I need a suggestion on how to switch to Fragments onTabSelected.
Unfortunately I cannot extend my MainActivity to FragmentActivity, since I won't be able to use ActionBar in that case (I am required to extend ActionBarActivity).
onTabSelected snippet:
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
int position = tab.getPosition();
switch (position) {
case 0:
break;
case 1:
break;
case 2:
break;
}
}
Part of MainActivity that matters here:
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Novice", "Članki", "O Tribuni" };
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getSupportActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(android.app.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) {
}
});
}
Any help / suggestion appreciated.
OK, I figured it out by myself guys.
The answer is to notify the viewPager about the TabSelected.
Use this line of code in your onTabSelected method:
mViewPager.setCurrentItem(tab.getPosition());
Hope it helps someone else too!
Instead of using an OnTabSelectedListener you can implement a FragmentPagerAdapter and forward the ViewPager events to the TabLayout:
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(...);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(new TabPagerAdapter(getSupportFragmentManager()));
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
This worked for me, so should work for you:
#Override
public void onTabSelected(android.support.v7.app.ActionBar.Tab tab, android.support.v4.app.FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition(),true);
drawerLayout.closeDrawers();
}

Tab+swipe Gesture, Custom grid view, Fragments

Well I have this app with swipe gesture functionality between fragments which they contains images which are located in the resources folders .. but when i swipe left and right I noticed that the performance is bad and slow .. Any suggestions to improve it?
And here is the header of the main activity code :
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = {"Roman Curtain", "Roller Blinds", "Wooden Blinds" ,"Kitchen Blinds"};
//
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initilization
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) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
and here is tab pager adapter :
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new RomanCurtains();
case 1:
return new RollerBlinds();
case 2:
return new WoodenBlinds();
case 3:
return new KitchenBlinds();
// case 4:
// return new KitchenBlinds();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 4;
}
}
There may be a two reason for the bad performance
Your images are too big and takes too much space in the memory
You can put the images in assets folder and then use Picasso library to use them. It will improve the performance.
https://github.com/square/picasso
All the pages in the ViewPager is in the memory if you use PagerAdapter or FragmentPagerAdapter.
If you use FragmentStatePagerAdapter only the visible page and the
pages adjacent to that page are kept in the memory. This will
improve the performance too.
Use ViewPager.setOffscreenPageLimit(int limit)

view pager with fragments having listview updating multiple times

I am trying to implement 3 fragments within View pager. All of the fragments has their own list view. Whenever i am swiping back to the first fragment the list view is updating itself getting duplicate values. here is the main activity implementing the view pager. Please suggest.
public class MainActivity extends FragmentActivity {
/** Called when the activity is first created. */
static AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
SearchView mSearchView;
MenuItem menuSearch;
Boolean flag = false;
String pid;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setupActionBar();
getActionBar().setTitle("All Patients");
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager, attaching the adapter and setting up a listener for when the
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new OnPageChangeListener()
{
public void onPageSelected(int position)
{
//mAppSectionsPagerAdapter.getItemPosition(getFragmentManager().findFragmentById(position));
//getActionBar().setTitle(mAppSectionsPagerAdapter.getPageTitle(position));
if(position==0){
getActionBar().setTitle("All Patients");
//flag = true;
//menuSearch.setVisible(true);
invalidateOptionsMenu();
}
if(position==1){
getActionBar().setTitle("All Doctors");
//flag=false;
//menuSearch.setVisible(false);
invalidateOptionsMenu();
}
else
getActionBar().setTitle("All Nurses");
invalidateOptionsMenu();
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
}
public void onPageScrollStateChanged(int state)
{
if (state == ViewPager.SCROLL_STATE_DRAGGING)
{
}
if (state == ViewPager.SCROLL_STATE_IDLE)
{
}
}
});
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
* sections of the app.
*/
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
// The first section of the app is the most interesting -- it offers
// a launchpad into the other demonstrations in this example application.
return new AllPatient();
case 1:
//Intent intent = new Intent(MainActivity.this,abc.class);
return new AllDoctors();
case 2:
return new AllNurses();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
Try this:
mViewPager.setOffscreenPageLimit(3);

Change tab color in Android

I have these codes for my two tabs. I would like to change the color but I dont know how to do it. Should it be done in my java file, or in my xml ? Thank You
Here are my codes
import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
import android.widget.TabHost;
// This is now the first activity that you see when you enter the app, it derives from TabActivity
public class TabsActivity extends TabActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
// The activity displays a TabHost layout with a TabWidget below the actual tab contents
setContentView(R.layout.tabs);
// Two tabs are added one displays the main list activity, the other an info activity
addNewTab("Kalender", MainActivity.class);
addNewTab("Info", InfoActivity.class);
}
// This function defines and adds a tab to the interface
private void addNewTab(String name, Class<? extends Activity> activityClass)
{
TabHost tabHost = getTabHost();
// The new tab will display a separate activity, so it needs an intent for it
Intent activityIntent = new Intent().setClass(this, activityClass);
// The TabSpec sets the internal name and the visible name of the newly created tab
TabHost.TabSpec spec = tabHost.newTabSpec(name).setIndicator(name).setContent(activityIntent);
// Finally, the new tab is added to the TabHost
tabHost.addTab(spec);
}
}
Changing text Color and Background color of TAB
for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
{
tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.WHITE); //Changing background color of tab
TextView tv = (TextView) tabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title); /*for Selected Tab changing text color*/
tv.setTextColor(Color.BLACK);
}
This is one way to make the background of a single tab have a color, and also to set one.
tabHost.getTabWidget().getChildAt(tabIndex).setBackgroundColor(color);
If you want to customize the look of your tabs, you should use your own tab widget. The thing is that most android widgets are themed using bitmaps, so you can't simply change the gradient color.
Some people suggest simply changing the backgroundColor of the standard widget, but it is going to look rather flat.
Using your own widget goes something like this:
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("artists").setIndicator("Artists",
res.getDrawable(R.drawable.ic_tab_artists))
.setContent(intent);
tabHost.addTab(spec);
Also have a look at the Android style guide's tab section.
Hey if you want to change the tab color just like in Google Playstore try this:
public class MainActivity extends AppCompatActivity implements TabLayout.BaseOnTabSelectedListener {
private AppBarLayout appBarLayout;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private View mRevealView;
private View mRevealBackgroundView;
private int fromColor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appBarLayout = findViewById(R.id.main_appbar);
toolbar = findViewById(R.id.main_toolbar);
tabLayout = findViewById(R.id.main_tablayout);
viewPager = findViewById(R.id.main_viewPager);
mRevealView = findViewById(R.id.reveal);
mRevealBackgroundView = findViewById(R.id.revealBackground);
setUpTabs();
setSupportActionBar(toolbar);
fromColor = R.color.colorTabOne;
}
private void setUpTabs() {
viewPager.setAdapter(new ViewPagerAdapter());
tabLayout.setupWithViewPager(viewPager);
tabLayout.addOnTabSelectedListener(this);
tabLayout.getTabAt(0).setText("TAB ONE");
tabLayout.getTabAt(1).setText("TAB TWO");
tabLayout.getTabAt(2).setText("TAB THREE");
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case 0:
animateAppAndStatusBar(0, R.color.colorTabOne);
break;
case 1:
animateAppAndStatusBar(appBarLayout.getWidth() / 2, R.color.colorTabTwo);
break;
case 2:
animateAppAndStatusBar(appBarLayout.getWidth(), R.color.colorTabThree);
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
private void animateAppAndStatusBar(int cx, final int toColor) {
Animator animator = ViewAnimationUtils.createCircularReveal(
mRevealView,
cx,
appBarLayout.getBottom(), 0,
appBarLayout.getWidth() / 2);
animator.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationStart(Animator animation) {
mRevealView.setBackgroundColor(getResources().getColor(toColor));
}
});
mRevealBackgroundView.setBackgroundColor(getResources().getColor(fromColor));
animator.setStartDelay(200);
animator.setDuration(125);
animator.start();
mRevealView.setVisibility(View.VISIBLE);
fromColor = toColor;
}
class ViewPagerAdapter extends FragmentPagerAdapter {
ViewPagerAdapter() {
super(MainActivity.this.getSupportFragmentManager());
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
return new TabOneFragment();
case 1:
return new TabTwoFragment();
case 2:
return new TabThreeFragment();
default:
throw new IllegalArgumentException("Invalid position " + i);
}
}
#Override
public int getCount() {
return 3;
}
}
}
You can check out my Github or Youtube tutorial

Categories

Resources