I'm implementing ActionBar tabs according to official guide.
I have a fragment that is added to activity. In that fragment I'm creating tabs:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
Tab tab = actionBar.newTab()
.setText("One")
.setTabListener(new TabListener<DemoFragment>(
this, "1", DemoFragment.class));
actionBar.addTab(tab);
tab = actionBar.newTab()
.setText("Two")
.setTabListener(new TabListener<DemoFragment>(
this, "2", DemoFragment.class));
actionBar.addTab(tab);
}
But these tabs are never displayed. Nor content of DemoFragment. Even though at runtime getActionBar().getTabCount() returns correct count of tabs. And I see that DemoFragment is initialized. All I see is ActionBar.
What am I doing wrong?
I'm not using any support libraries as I'm developing for minSdk=14.
Update
IF YOUR NOT USING ANY SUPPORT LIBRARY THIS SHOULD WORK
otherwise you will have to use the getSupportActionBar() and above mentioned dependencies.
Try something more like this:
// Get the Instance of the Action Bar, set Navigation Mode, remove title
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
// One tab
actionBar.addTab(actionBar.newTab() .setText("One")
.setTabListener(new TabListener<DemoFragment>(
this, "1", DemoFragment.class)));
// Two tab
actionBar.addTab(actionBar.newTab()
.setText("Two")
.setTabListener(new TabListener<DemoFragment>(
this, "2", DemoFragment.class)));
Edit to Post - Working Code that I have used for a demo
Here is code from a demo Application That i wrote using Android sdk 14 Just like you are.
public class MainActivity extends Activity {
// String Titles
static String [] titles = {"Fragment 1", "Fragment 2"};
static String [] fragmentClasses = {Fragment1.class.getName(), Fragment2.class.getName()};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SimpleTabListener.SetUpTabNavigation(this, fragmentClasses, titles);
}
And here is the SimpleTabListener Class
public class SimpleTabListener implements TabListener {
Context m_context;
String m_fragmentClassName ;
Fragment m_fragment = null;
public SimpleTabListener(Context context, String tabFragmentClassName)
{
m_context = context;
m_fragmentClassName = tabFragmentClassName;
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft)
{
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft)
{
if(m_fragment == null)
{
m_fragment = Fragment.instantiate(m_context, m_fragmentClassName);
ft.add(android.R.id.content, m_fragment);
}else
{
ft.attach(m_fragment);
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft)
{
// TODO Auto-generated method stub
if(m_fragment != null){
// TODO Auto-generated method stub
ft.detach(m_fragment);
}
}
public static void SetUpTabNavigation(Activity activity, String [] classNames, String [] tabTitles){
ActionBar actionBar = activity.getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener listener;
for(int i = 0; i < tabTitles.length; i++)
{
listener = new SimpleTabListener(activity, classNames[i]);
actionBar.addTab(actionBar.newTab().setText(tabTitles[i]).setTabListener(listener));
}
}
}
Frament1.class
public class Fragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.fragment_1, container, false);
}
}
Fragment 2.class
public class Fragment2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.fragment2, container, false);
}
}
Related
I'm using a SlidingTabLayout (from the Google sources) in my app to navigate between different fragments.
I can swipe between contents just fine, but the problem I'm facing is the title of the Action bar that is acting weird.
Suppose that I have two tabs with two titles ('First Title' and 'Second Title') :
| Action bar |
| First Title | Second Title |
When I first enter the Fragment containing the SlidingTabLayout, the title of the Actionbar is like this :
| Firs... |
| First Title | Second Title |
When I swipe (to the second tab for example), the title of the actionbar becomes :
| Second Title |
| First Title | Second Title |
And stays like this. It seems that the Actionbar takes the title of the last Fragment loaded when I swipe at least once.
What I want is this :
I want to show a 'Main Title' in the Actionbar that never changes no matter what the title in the SlidingTabLayout is.
Here are some portions of my code:
** Fragment containing the SlidingTabLayout:
private String mainTitle;
....
#Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
// The mainTitle is given to this fragment by another fragment
Bundle args = getArguments();
if (args != null) {
mainTitle = args.getString("TITLE");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.layout, container, false);
mViewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
mSlidingLayout = (SlidingTabLayout) rootView.findViewById(R.id.sliding_layout);
List<Fragment> listFragments = new ArrayList<>();
List<String> listTitles = new ArrayList<>();
for (int i = 0; i < mSize; i++) {
Bundle bundle = new Bundle();
....
listFragments.add(Fragment.instanciate(getActivity(), CustomFragment.class.getName(), bundle));
listTitles.add("...");
}
mViewPager.setAdapter(new PagerAdapter(getChildFragmentManager(), listFragments, listTitles));
mSlidingLayout.setDistributedEvenly(true);
mSlidingLayout.setViewPager(mViewPager);
return rootView;
}
#Override
public void onResume() {
super.onResume();
// I TRY TO SET THE TITLE HERE !!
getActivity().getSupportActionBar().setTitle(mainTitle);
}
** Adapter:
class PagerAdapter extends FragmentPagerAdapter {
List<Fragment> fragments;
List<String> titles;
...
#Override
public Fragment getItem(int position) {
Fragment fragment = fragments.get(position);
return fragment;
}
#Override
public CharSequence getPageTitle(int position) {
// maybe the problem is in this method.
// this method is supposed to provide the titles for the tab
// but maybe it's also changing the actionbar title
return titles.get(position);
}
I'm setting the title of the ActionBar in the onResume method every time I enter a Fragment.
Thanks !
EDIT 1 :
I tried using the new SlidingTabLayout which I've got from the Google I/O, and the result is still the same !
It seems that the Title in the ActionBar is a hint at first, and then it changes to the last loaded fragment when I swipe to another fragment.
It's like it's loading fragment, and each time a fragment is loaded, the title in the ActionBar is overridden with the title of that fragment.
EDIT 2 :
I changed my code to post the latest version of it (I'm using now a SlidingTabLayout) and to show how I get my mainTitle.
you can use below code it works fine for me
public class MatchesActivity extends AppCompatActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
FloatingActionButton skipButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_matches);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
skipButton = (FloatingActionButton) findViewById(R.id.skip_next);
skipButton.setVisibility(View.GONE);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOffscreenPageLimit(1);
mViewPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return false;
}
});
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
actionBar.addTab(
actionBar.newTab().setText("MATCHES")
.setTabListener(this));
actionBar.addTab(
actionBar.newTab().setText("PINS")
.setTabListener(this));
actionBar.addTab(
actionBar.newTab().setText("CHATS")
.setTabListener(this));
}
#Override
public void onBackPressed() {
startActivity(new Intent(MatchesActivity.this, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK & Intent.FLAG_ACTIVITY_CLEAR_TOP));
MatchesActivity.this.finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new MatchesFragment();
case 1:
return new PinsFragment();
case 2:
return new ConversationFragment();
default:
return new MatchesFragment();
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
}
I am posting here a code of mine.It worked for me.Make required changes in it and try it.I used PagerSlidingTabStrip library in it.
public class DealFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_deal, container, false);
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
viewPager.setAdapter(new SampleFragmentPagerAdapter(getChildFragmentManager()));
PagerSlidingTabStrip tabsStrip = (PagerSlidingTabStrip)view.findViewById(R.id.tabs);
tabsStrip.setBackgroundColor(Color.parseColor("#333333"));
// Attach the view pager to the tab strip
tabsStrip.setViewPager(viewPager);
return view;
}
public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 2;
private final String tabTitles[] = new String[] { "Today's Deals", "Deals Close By" };
public SampleFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
if(position==0)
{
return new TodaysDeal();
}
else
{
return new DealsCloseBy();
}
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
}
}
hope it might help you.
The actionBar title doesn't change because onResume() is not called the time you swipe back.
It's because ViewPager doesn't call fragment's onResume the second time. Even though in reality the fragment is resumed.
What you can do is to move the setting of your actionbar title in your parent fragment (that contains pagertabstrip) to onCreateView instead.
For your reference:
** Fragment containing the PagerTabStrip:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.layout, container, false);
mViewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
List<Fragment> listFragments = new ArrayList<>();
List<String> listTitles = new ArrayList<>();
...
// HERE's what you want
final ActionBar actionBar = getActivity().getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(R.string.main_title);
}
mViewPager.setAdapter(new PagerAdapter(getChildFragmentManager(), listFragments));
return rootView;
}
Found it !
It was really dumb of me (it explains why others didn't have this problem)
I was setting the title also in each of the Fragments (even those contained in the Tabs), so when I swiped, the onResume on those Fragments was called and it changed the title in the ActionBar...
Thank you all for the help, I appreciate it !
I am using ViewPager / FragmentPagerAdapter in one of my application fragments to display different listviews in each page (see the picture below) :
The problem is that after i change the current view (Fragment) and i reopen it again, the listview isn't rendered (see the picture below) :
The behaviour is random, sometimes the listview are shown when i slide between different tabs/pages.
Here is my fragment code :
public class AstucesFragment extends Fragment implements ActionBar.TabListener {
ActionBar actionBar;
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
public static String[] tabslist = new String[5];
public AstucesFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_astuces, container, false);
tabslist[0] = getActivity().getResources().getString(R.string.astuces_quotidien);
tabslist[1] = getActivity().getResources().getString(R.string.astuces_resto);
tabslist[2] = getActivity().getResources().getString(R.string.astuces_loisirs);
tabslist[3] = getActivity().getResources().getString(R.string.astuces_transports);
tabslist[4] = getActivity().getResources().getString(R.string.astuces_tous);
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getActivity().getSupportFragmentManager());
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mViewPager = (ViewPager) view.findViewById(R.id.astuces_pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
actionBar.addTab(
actionBar.newTab()
.setCustomView(R.layout.fragment_astuces_tabs_quotidien)
.setTabListener(this));
actionBar.addTab(
actionBar.newTab()
.setCustomView(R.layout.fragment_astuces_tabs_resto)
.setTabListener(this));
actionBar.addTab(
actionBar.newTab()
.setCustomView(R.layout.fragment_astuces_tabs_loisirs)
.setTabListener(this));
actionBar.addTab(
actionBar.newTab()
.setCustomView(R.layout.fragment_astuces_tabs_transports)
.setTabListener(this));
actionBar.addTab(
actionBar.newTab()
.setCustomView(R.layout.fragment_astuces_tabs_tous)
.setTabListener(this));
return view;
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
Log.i("AstucesFragment","onTabSelected()");
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
Log.i("AstucesFragment","onTabReselected()");
}
/**
* A {#link android.support.v4.app.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) {
Log.i("AppSectionsPagerAdapter","Page ID : "+i);
// The other sections of the app are dummy placeholders.
Fragment fragment = new AstucesListFragment();
Bundle args = new Bundle();
args.putString(AstucesListFragment.ARG_PAGE_CAT, tabslist[i]);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return tabslist.length;
}
#Override
public CharSequence getPageTitle(int position) {
return tabslist[position];
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
}
}
/**
* A dummy fragment representing a section of the app, but that simply displays dummy text.
*/
public static class AstucesListFragment extends Fragment {
public static final String ARG_PAGE_CAT = "page_cat";
private List<Astuce> astuceList = new ArrayList<Astuce>();
private ListView listView;
private AstuceAdapter adapter;
private AstuceDAO astuceDAO;
public AstucesListFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_astuces_page, container, false);
Bundle args = getArguments();
Log.i("AstucesListFragment","onCreateView()");
String theme = "";
if (args.getString(ARG_PAGE_CAT) == getString(R.string.astuces_quotidien)) theme = "Q";
else if (args.getString(ARG_PAGE_CAT) == getString(R.string.astuces_resto)) theme = "R";
else if (args.getString(ARG_PAGE_CAT) == getString(R.string.astuces_loisirs)) theme = "L";
else if (args.getString(ARG_PAGE_CAT) == getString(R.string.astuces_transports)) theme = "T";
else theme = "";
astuceDAO = new AstuceDAO();
astuceList = astuceDAO.findAstuceByTheme(theme);
listView = (ListView) rootView.findViewById(R.id.astuces_list);
adapter = new AstuceAdapter(getActivity(), astuceList);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return rootView;
}
}
}
How can i fix this problem ?
If you want your fragments to maintain its state even after changing the tabs,
Try this,
mViewPager.setOffscreenPageLimit(5); //as you have 5 fragments
But this will make the activity to initialize all the fragments at the same time when the activity is invoked.
Another method is to use FragmentStatePagerAdapter instead of FragmentPagerAdapter. Refer,
http://developer.android.com/reference/android/support/v4/app/FragmentStatePagerAdapter.html
You are not comparing strings correctly. When comparing two strings you need to use equals() method instead of == operator. So in onCreateView() in AstucesListFragment replace
if (args.getString(ARG_PAGE_CAT) == getString(R.string.astuces_quotidien)) theme = "Q";
else if (args.getString(ARG_PAGE_CAT) == getString(R.string.astuces_resto)) theme = "R";
else if (args.getString(ARG_PAGE_CAT) == getString(R.string.astuces_loisirs)) theme = "L";
else if (args.getString(ARG_PAGE_CAT) == getString(R.string.astuces_transports)) theme = "T";
else theme = "";
with
if (args.getString(ARG_PAGE_CAT).equals(getString(R.string.astuces_quotidien))) theme = "Q";
else if (args.getString(ARG_PAGE_CAT).equals( getString(R.string.astuces_resto))) theme = "R";
else if (args.getString(ARG_PAGE_CAT).equals( getString(R.string.astuces_loisirs))) theme = "L";
else if (args.getString(ARG_PAGE_CAT).equals( getString(R.string.astuces_transports))) theme = "T";
else theme = "";
This may solve your problem as the results of == operators will be inconsistent as both the strings may or may not point to same object.
I am writing a program in which i am using Fragments to work with Tabs, but i need few changes in my UI
I need few changes in my UI, small 5 questions:
Question 1: How to Change Background color of TITLE BAR (I want RED)
Question 2: How to Change Background color of Tab (I want GRAY)
Question 3: How to Change color of Selected Tab (I want RED)
Question 4: How to show Icon above the Text in Tabs
Question 5: How to place share button over Title Bar at Right side
Manifest.xml:
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.test.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
MainActivity.java:
public class MainActivity extends FragmentActivity {
ViewPager ViewPager;
TabsAdapter TabsAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//create a new ViewPager and set to the pager we have created in Ids.xml
ViewPager = new ViewPager(this);
ViewPager.setId(R.id.pager);
setContentView(ViewPager);
//Create a new Action bar and set title to strings.xml
final ActionBar bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setTitle(R.string.app_name);
//Attach the Tabs to the fragment classes and set the tab title.
TabsAdapter = new TabsAdapter(this, ViewPager);
TabsAdapter.addTab(bar.newTab().setText("About"),
FragAbout.class, null);
TabsAdapter.addTab(bar.newTab().setText("Location"),
FragLocation.class, null);
TabsAdapter.addTab(bar.newTab().setText("Menus"),
FragMenus.class, null);
TabsAdapter.addTab(bar.newTab().setText("Reservation"),
FragReservation.class, null);
TabsAdapter.addTab(bar.newTab().setText("Social"),
FragSocial.class, null);
if (savedInstanceState != null) {
bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
}
// create TabsAdapter to create tabs and behavior
public static class TabsAdapter extends FragmentPagerAdapter
implements ActionBar.TabListener, ViewPager.OnPageChangeListener {
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
static final class TabInfo {
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args) {
clss = _class;
args = _args;
}
}
public TabsAdapter(FragmentActivity activity, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = activity.getActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
#Override
public void onPageScrollStateChanged(int state) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
mActionBar.setSelectedNavigationItem(position);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Object tag = tab.getTag();
for (int i=0; i<mTabs.size(); i++) {
if (mTabs.get(i) == tag) {
mViewPager.setCurrentItem(i);
}
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
#Override
public int getCount() {
return mTabs.size();
}
}
FragAbout.java:
public class FragAbout extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.frag_about, container, false);
return myFragmentView;
}
}
I think you already got the answer, that's why you developed this:
https://stackoverflow.com/questions/19000981/actionbarsherlock-swapping-tabs-using-viewpager
Anyways if you still looking for answer, So
I really recommend you to use ActionBarStyleGenerator:
http://jgilfelt.github.io/android-actionbarstylegenerator/
With that tool you can easily theme your graphic elements in your toolbar.
use this for QA:2,3,4
create xml(tab1) in drawble folder
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- When selected, use grey -->
<item android:drawable="#drawable/videos_gray"
android:state_selected="true" />
<!-- When not selected, use white-->
<item android:drawable="#drawable/videos_white" />
and use that in java file
// Create an actionbar
ActionBar actionBar = getActionBar();
// Hide Actionbar Icon
actionBar.setDisplayShowHomeEnabled(false);
// Hide Actionbar Title
actionBar.setDisplayShowTitleEnabled(false);
// Create Actionbar Tabs
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create first Tab
tab = actionBar.newTab().setTabListener(new FragmentTab1());
// Create your own custom icon
tab.setIcon(R.drawable.tab1);
actionBar.addTab(tab);
// Create Second Tab
tab = actionBar.newTab().setTabListener(new FragmentTab2());
// Set Tab Title
tab.setText("Tab2");
actionBar.addTab(tab);
// Create Third Tab
tab = actionBar.newTab().setTabListener(new FragmentTab3());
// Set Tab Title
tab.setText("Tab3");
actionBar.addTab(tab);
Ans for Q.1 :
You can make a new layout and set its Height at desired "dp" and change the background of that layout to Red color (use resource for that - preferably define a color using color code OR bring in image with Red background). This does not involve using fragments.
Ans for Q.5:
If you use my option as above, use RelatieLayout for Title bar. Then position the button you want at the rightmost side.(Use gravity or manually drag or android:layout_alignParentRight="true" - whichever way you want)
Can't say anything about other questions. Hope this helps
Some other Links:
How do I change the background of an Android tab widget?
I created my Sherlock fragment activity and implemented tabs:
public class Home extends SherlockFragmentActivity
{
ActionBar actionBar;
TabHost myTabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
actionBar=getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tab1= actionBar.newTab();
ActionBar.Tab tab2= actionBar.newTab();
//ActionBar.Tab tab3 = actionBar.newTab();
tab1.setText("Contacts");
tab2.setText("Inbox");
// tab3.setText("Outbox");
tab1.setTabListener(new MyTabListener());
tab2.setTabListener(new MyTabListener());
actionBar.addTab(tab1, true);
actionBar.addTab(tab2);
actionBar.addTab(tab3);
}
And this is my tab change listener:
private class MyTabListener implements TabListener
{
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if(tab.getPosition()==0)
{
FragmentA frag = new FragmentA ();
ft.replace(android.R.id.content, frag );
}
else
{
FragmentB frag = new FragmentB ();
ft.replace(android.R.id.content,frag );
}
}
And this is my FragmentA:
public class FragmentA extends Fragment
{
TextView textView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return inflater.inflate(R.layout.activity_list, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
}
}
Here under my first tab, there is a list that is displaying. When I click any one of the list items, I need to load another fragment under the same activity. And when back is pressed, the old fragment needs to be loaded under the same tab.
Is this possible in actionbarsherlock tabs? If so, how do I do this?
Is it possible to display tabs without using fragments in android 3.0?I have created actionbar with tabs extending fragments.But without using fragments and by extending activity will i be able to display tabs.I need to achieve that.pls help.I have posted my code also.
Java Code :
public class ActionbarActivity extends Activity {
ActionBar bar;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ActionBar bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tabA = bar.newTab().setText("Home");
ActionBar.Tab tabB = bar.newTab().setText("Listings");
ActionBar.Tab tabC = bar.newTab().setText("Remote");
Fragment fragmentA = new ATab();
Fragment fragmentB = new BTab();
Fragment fragmentC = new CTab();
bar.setDisplayShowHomeEnabled(true);
tabA.setTabListener(new MyTabsListener(fragmentA));
tabB.setTabListener(new MyTabsListener(fragmentB));
tabC.setTabListener(new MyTabsListener(fragmentC));
bar.addTab(tabA);
bar.addTab(tabB);
bar.addTab(tabC);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option, menu);
return true;
}
protected class MyTabsListener implements ActionBar.TabListener {
private Fragment mfragment;
public MyTabsListener(Fragment fragment) {
this.mfragment = fragment;
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.add(R.id.fragment_place, mfragment, null);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
ft.remove(mfragment);
}
}
}
public class ATab extends Fragment
{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return inflater.inflate(R.layout.atab, container, false);
}
}
public class BTab extends Fragment
{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return inflater.inflate(R.layout.btab, container, false);
}
}
public class CTab extends Fragment
{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return inflater.inflate(R.layout.ctab, container, false);
}
}
xml.code :
<?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"
>
<LinearLayout android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="#+id/fragment_place"></LinearLayout>
</RelativeLayout>
You don't have to use fragments to use tabs and I've successfully done this within one of my apps, just changing content on tab selection.
public class Main extends Activity implements ActionBar.TabListener {
int mDisplayMode;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
mDisplayMode = settings.getInt("displayMode", 0);
ActionBar actionBar = getActionBar();
actionBar.addTab(
actionBar.newTab().setText("Decimal").setTabListener(this)
);
actionBar.addTab(
actionBar.newTab().setText("Hexadecimal").setTabListener(this)
);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.selectTab(actionBar.getTabAt(mDisplayMode));
// Other code
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mDisplayMode = tab.getPosition();
// do stuff based on new tab selected
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// do nothing
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// do nothing
}
// ..
}