I have created an application having action bar and two tabs in it. The tabs and the title of the application are in the same line as given in the screenshot. I want the tabs to be in the line below the title and having equal weight. Please have a look at the code below and help me out. Thanks.
package com.example.myproj;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ActionBar.Tab;
import android.content.Context;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity1 extends Activity {
public static Context appContext;
static ArrayList<String> myarray = new ArrayList();
static ArrayList<String> myarray1;
static ArrayList<String> myarray2 = new ArrayList();
static ArrayList<String> myarray21;
static int check1 = 0;
static int check2 = 0;
static int stcount = 0;
static int csicount = 0;
static ActionBar.Tab PlayerTab;
static ActionBar.Tab StationsTab;
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
appContext = getApplicationContext();
ActionBar actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
PlayerTab = actionbar.newTab().setText("ST");
StationsTab = actionbar.newTab().setText("CSI");
// settab1("Testing");
Fragment PlayerFragment = new AFragment();
Fragment StationsFragment = new BFragment();
PlayerTab.setTabListener(new MyTabsListener(PlayerFragment));
StationsTab.setTabListener(new MyTabsListener(StationsFragment));
actionbar.addTab(PlayerTab);
actionbar.addTab(StationsTab);
}
public static void settab1(String text) {
PlayerTab.setText(text);
}
public static void settab2(String text) {
StationsTab.setText(text);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
class MyTabsListener implements ActionBar.TabListener {
public Fragment fragment;
public MyTabsListener(Fragment fragment) {
this.fragment = fragment;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(MainActivity1.appContext, "Reselected!",
Toast.LENGTH_LONG).show();
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.replace(R.id.fragment_container, fragment);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(fragment);
}
}
I had luck using the following reflection 'hack':
private void forceStackedTabs() {
ActionBar ab = getSupportActionBar();
if ( ab instanceof ActionBarImpl ) {
// Pre-ICS
disableEmbeddedTabs( ab );
} else if ( ab instanceof ActionBarWrapper ) {
// ICS
try {
Field abField = ab.getClass().getDeclaredField( "mActionBar" );
abField.setAccessible( true );
disableEmbeddedTabs( abField.get( ab ) );
} catch (NoSuchFieldException e) {
Log.e( TAG, "Error disabling actionbar embedded", e );
} catch (IllegalArgumentException e) {
Log.e( TAG, "Error disabling actionbar embedded", e );
} catch (IllegalAccessException e) {
Log.e( TAG, "Error disabling actionbar embedded", e );
}
}
}
private void disableEmbeddedTabs(Object ab) {
try {
Method setHasEmbeddedTabsMethod = ab.getClass().getDeclaredMethod("setHasEmbeddedTabs", boolean.class);
setHasEmbeddedTabsMethod.setAccessible(true);
setHasEmbeddedTabsMethod.invoke(ab, false);
} catch (Exception e) {
Log.e( TAG, "Error disabling actionbar embedded", e );
}
}
Please note that I didn't think of this myself, but simply rewrote the code given in this answer: replicate ActionBar Tab(s) with custom view
This is the behavior of the native action bar.
The action bar alone decides whether or not to put the tabs on a second row, and we cannot influence that.(Usually in tablet tabs are inline, in phones are below)
If you want to ensure that your tabs are always tabs, and are always below the action bar, remove the tabs from the action bar and switch to using a ViewPager for your content, with either PagerTabStrip (from the Android Support package, where ViewPager comes from) or the tab indicator from the ViewPagerIndicator project for the tabs themselves.
As a side benefit, your contents are now horizontally swipe-able to move between tabs, which is a popular approach.
Just a note. It is not a right pattern.
http://developer.android.com/design/patterns/pure-android.html
Here is a demo which may be help you!I use a customview in actionbar which is contains a TabHost,It can work out well like the picture above,but I don't test it in different screen sizes.
https://github.com/shellshy/actionbar
In ActionBarImpl.java, in the setHasEmbeddedTabs(boolean hasEmbeddedTabs) method,
change the value:
mHasEmbeddedTabs = hasEmbeddedTabs;
to:
mHasEmbeddedTabs = false;
Related
am following the Android Developers website to add sliding tabs to my Android app for my project, I am stuck with this one error and do not understand the problem, I know it has something to do with calling the correct Fragment layout, I am doing exactly what the tutorial tells me too, have any of you guys got any information to solve this, thank you.
package com.test.finalproject;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends FragmentActivity implements View.OnClickListener {
DemoCollectionPagerAdapter mCollectionPagerAdapter;
ViewPager mViewPager;
Button buttonLogin;
Button buttonRegister;
Button buttonTheme;
Button buttonMaps;
#Override
protected void onCreate(Bundle savedInstanceState) {
Utils.setThemeToActivity(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final android.app.ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create a tab listener that is called when the user changes tabs.
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
// show the given tab
}
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
// hide the given tab
}
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
// probably ignore this event
}
};
// Add 3 tabs, specifying the tab's text and TabListener
for (int i = 0; i < 3; i++) {
actionBar.addTab(
actionBar.newTab()
.setText("Tab " + (i + 1))
.setTabListener(tabListener));
}
buttonLogin = (Button)findViewById(R.id.buttonLogin);
buttonLogin.setOnClickListener(this);
buttonRegister = (Button)findViewById(R.id.buttonRegister);
buttonRegister.setOnClickListener(this);
buttonTheme = (Button)findViewById(R.id.buttonTheme);
buttonTheme.setOnClickListener(this);
buttonMaps = (Button)findViewById(R.id.buttonMaps);
buttonMaps.setOnClickListener(this);
mCollectionPagerAdapter =
new DemoCollectionPagerAdapter(
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mCollectionPagerAdapter);
}
public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
// Our object is just an integer :-P
args.putInt(DemoObjectFragment.ARG_OBJECT, i + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 100;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated
// properly.
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText(
Integer.toString(args.getInt(ARG_OBJECT)));
return rootView;
}
}
public void onCreate1(Bundle savedInstanceState) {
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between pages, select the
// corresponding tab.
getActionBar().setSelectedNavigationItem(position);
}
});
}
private void buttonLoginClick()
{
startActivity (new Intent("MainApp"));
}
private void buttonRegisterClick()
{
startActivity (new Intent("TextToo"));
}
private void buttonThemeClick()
{
startActivity (new Intent("SettingsTheme"));
}
private void buttonMapsClick()
{
startActivity (new Intent("GoogleMaps"));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.buttonLogin:
buttonLoginClick();
break;
}
switch (v.getId())
{
case R.id.buttonRegister:
buttonRegisterClick();
break;
}
switch (v.getId())
{
case R.id.buttonTheme:
buttonThemeClick();
break;
}
switch (v.getId())
{
case R.id.buttonMaps:
buttonMapsClick();
break;
}
}
}
The Error is on line 126.
The Error is: Description Resource Path Location Type
fragment_collection_object cannot be resolved or is not a field MainActivity.java /Login/src/com/test/finalproject line 126 Java Problem
The problem you are facing is because of the missing xml file in the layout folder of project/res
Go to http://developer.android.com/training/implementing-navigation/lateral.html
Click on "download the sample app" and unzip it. Add the EffectiveNavigation\res\layout\fragment_collection_object.xml to you project\res\layout. This,I guess will solve the problem.
I have followed the example
https://github.com/astuetz/PagerSlidingTabStrip
by extracting the resources xml attributes and Pager class to implement into my class such that the tab indicator color is not pale blue but other colors by setting SetIndicator
When it comes tto the implementation, it seems that I cannot change the color as wished. Would you please tell me how to import the library project or other ways such that I can change the tab indicator color?
The below is my code:
import android.os.Bundle;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.FragmentTransaction;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class MainActivity extends FragmentActivity implements TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs ;
private PagerSlidingTabStrip strip;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Initilization
strip = (PagerSlidingTabStrip) findViewById(R.id.tabs);
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.BLACK));
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
strip.setIndicatorColor(Color.parseColor("#00ffbf"));
// strip.setShouldExpand(true);
//strip.setIndicatorColor(Color.parseColor("#00ffbf"));
// strip.setViewPager(viewPager);
// Adding Tabs
tabs = this.getResources().getStringArray(R.array.options);
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);
//actionBar.getTabAt(position).getCustomView().setBackgroundColor(Color.parseColor("#00ffbf"));
}
#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());
// tab.set
//
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
#Override
protected void onResume() {
super.onResume();
// mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
super.onPause();
// mSensorManager.unregisterListener(mSensorListener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
/* if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}*/
// Handle action buttons
switch(item.getItemId()) {
/* case R.id.action_profile:
startActivity(new Intent(MainActivity.this, Profile.class));
return true;*/
default:
return super.onOptionsItemSelected(item);
}
}
}
parseColor() supports two formats: #RRGGBB and #AARRGGBB, Have you tried with the alpha format?:
strip.setIndicatorColor(Color.parseColor("#ff00ffbf"));
If that doesn't work, you can try changing the default color directly from the PagerSlidingTabStrip class:
private int indicatorColor = 0xFF00FFBF;
Try this,in easy way
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="#android:color/white" />
I've been trying to add tabs to the action bar while going through a few Android tutorials, but every time I use addTab, something breaks. My code currently looks like this:
package com.example.myfirstapp;
import android.app.ActionBar;
import android.app.ActionBar.TabListener;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends FragmentActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ActionBar actionBar = getActionBar();
// actionBar.setSubtitle("mytest");
actionBar.setTitle("Title Goes Here");
// Set up the action bar to show tabs.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Here are a couple tabs
ActionBar.Tab PlayerTab = actionBar.newTab().setText("Fragment A");
ActionBar.Tab StationsTab = actionBar.newTab().setText("Fragment B");
// for each of the sections in the app, add a tab to the action bar.
actionBar.addTab(PlayerTab);
actionBar.addTab(StationsTab);
// Create a tab listener that is called when the user changes tabs.
// ActionBar.TabListener tabListener = new ActionBar.TabListener() {
// public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
// // show the given tab
// }
//
// public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
// // hide the given tab
// }
//
// public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
// // probably ignore this event
// }
// };
//
// // Add 3 tabs, specifying the tab's text and TabListener
// for (int i = 0; i < 3; i++) {
// actionBar.addTab(
// actionBar.newTab()
// .setText("Tab " + (i + 1))
// .setTabListener(tabListener));
// }
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// First run
// getMenuInflater().inflate(R.menu.main, menu);
// return true;
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
public void openSearch() {
Toast.makeText(this, "Search button pressed", Toast.LENGTH_SHORT).show();
}
public void openSettings() {
Toast.makeText(this, "Settings pressed", Toast.LENGTH_SHORT).show();
}
// Finding selected option item
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
openSearch();
// menuItem = item;
// menuItem.setActionView(R.layout.progressbar);
// menuItem.expandActionView();
// TestTask task = new TestTask();
// task.execute("test");
// break;
return true;
case R.id.action_settings:
openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
// Do something in response to button
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
If I comment out the lines with
actionBar.addTab(PlayerTab);
actionBar.addTab(StationsTab);
the code works okay (shows a blank tabs bar), but once I add them in, my app crashes.
As per the docs for FragmentActivty:
If you want to implement an activity that includes an action bar, you
should instead use the ActionBarActivity class, which is a subclass of
this one, so allows you to use Fragment APIs on API level 7 and
higher.
FragmentActivity's getActionBar() is for API 11+. If your minSDKVersion is 11+ you should use the android.app.Activity version of Activity and get a reference of the ActionBar like you are doing now. If you want to be able to use Fragments and the ActionBar use ActionBarActivity which is part of the v7 support library
I tried to implement 3 tabs in android using the google tutorial.....but i am unable to create different activities for each one and navigate through them....
package com.example.tab;
import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Important-the following code in onCreate class adds tabs to action
// bar
final ActionBar actionBar = getActionBar();
// Specify that tabs should be displayed in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create a tab listener that is called when the user changes tabs.
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
// show the given tab
}
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction ft) {
// hide the given tab
}
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction ft) {
// probably ignore this event
}
};
// Now we add 3 Tabs specifying tab names and Tablistener
for (int i = 0; i < 3; i++) {
if (i == 0) {
actionBar.addTab(actionBar.newTab().setText("Tech")
.setTabListener(tabListener));
}
if (i == 1) {
actionBar.addTab(actionBar.newTab().setText("Politics")
.setTabListener(tabListener));
}
if (i == 2) {
actionBar.addTab(actionBar.newTab().setText("Sports")
.setTabListener(tabListener));
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) { // Method to add action bar
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_bar, menu);
return super.onCreateOptionsMenu(menu);
}
}
What should I try after this and creating 3 activities for each tab??
You should create just one Activity with a ViewPager and multiple Fragments (one for each tab). This tutorial describes how to do this.
Next you can listen for the selection of an action bar tab to change the viewpager and vice versa.
You should use FragmentActivity and Fragment for Tab and its different view in Activity.
see here for ActionBar Tab and for Fragment
I'm quite new to Android programming but I'll do my best to give all the information needed. I'm using the new android.support.v7.app.ActionBarActivity and android.support.v4.app.Fragment to display a Tab Layout for Android API from 8 to 17.
I'm facing a problem showing my two fragments correctly in my activity because they overlay each other after I select one of them. So, this is my main activity code:
package it.koopa.scank;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends ActionBarActivity {
private final static String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//have to use getSupportActionBar from android.support.v7.app
ActionBar actionBar = getSupportActionBar();
//hello tab
Tab tab = actionBar.newTab()
.setText(R.string.tab_hello)
.setTabListener(new TabListener<HelloFragment>(this, "hello", HelloFragment.class));
actionBar.addTab(tab);
//handle content tab
tab = actionBar.newTab()
.setText(R.string.tab_send)
.setTabListener(new TabListener<HandleContentFragment>(this, "handle", HandleContentFragment.class));
actionBar.addTab(tab);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.scank, menu);
return true;
}
public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
private Fragment mFragment;
private final ActionBarActivity mActivity;
private final String mTag;
private final Class<T> mClass;
/**
* Constructor used each time a new tab is created.
* #param activity The host Activity, used to instantiate the fragment
* #param tag The identifier tag for the fragment
* #param clz The fragment's Class, used to instantiate the fragment
*/
public TabListener(ActionBarActivity activity, String tag, Class<T> clz) {
mActivity = activity;
mTag = tag;
mClass = clz;
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mFragment = mActivity.getSupportFragmentManager().findFragmentByTag(mTag);
// Check if the fragment is already initialized
if (mFragment == null) {
// If not, instantiate and add it to the activity
mFragment = Fragment.instantiate(mActivity, mClass.getName());
ft.add(getCorrectActionBarId(), mFragment, mTag);
Log.i(TAG, "FragID " + mFragment.getId() + ", FragTAG=" + mFragment.getTag() + " ADDED!!!");
} else {
// If it exists, simply attach it in order to show it
ft.attach(mFragment);
Log.i(TAG, "FragID " + mFragment.getId() + ", FragTAG=" + mFragment.getTag() + " attached.");
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(mFragment);
Log.i(TAG, "FragID " + mFragment.getId() + ", FragTAG=" + mFragment.getTag() + " detached.");
}
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// User selected the already selected tab. Usually do nothing.
}
}
/**
* Returns the correct id of the action bar
* #return
*/
public static int getCorrectActionBarId () {
int androidVersion = Build.VERSION.SDK_INT;
if (androidVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return android.R.id.content;
} else {
return R.id.action_bar_activity_content;
}
}
}
And these are my two fragments (both use their own xml layout). First one:
package it.koopa.scank;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class HelloFragment extends Fragment {
private int index;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.hello, container, false);
Log.i("HelloFragment","I'm " + HelloFragment.class);
return v;
}
}
and second one:
package it.koopa.scank;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class HandleContentFragment extends Fragment {
private int index;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.handle_content, container, false);
Log.i("HandleContentFragment","I'm " + HandleContentFragment.class);
return v;
}
}
and, as a result, if I select the second tab, the views are put one over another!
I found a similar question here Tabs using android.support.v7.app.ActionBar but the accepted solution doesn't seem to work for me. In fact, in my main activity you can see I get the content id with
int androidVersion = Build.VERSION.SDK_INT;
if (androidVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return android.R.id.content;
} else {
return R.id.action_bar_activity_content;
}
but fragments content is still overlaied (I can't upload images because of my almost-zero reputation).
Where am I wrong?
Update:
My activity uses android:theme="#style/Theme.AppCompat.Light". I'm testing on a Nexus i9250 with Android 4.2.1
This is a known bug.
You can find a workaround here:
https://code.google.com/p/android/issues/detail?id=58602
Have every Fragment implement ActionBar.TabListener. Add these methods below along with the other code in your fragment
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mFragment = new MyFragment();
ft.add(android.R.id.content, mFragment);
ft.attach(mFragment);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(mFragment);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
You can remove the tab listener from your main activity. This handles all of it.
Just call ft.show(mfragment) method in onTabSelected and ft.hide(mfragment) method in onTabUnselected.
Look below
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.show(mfragment);
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.hide(mfragment);
}