i'm working on application in eclipse that have 5 tab and i have spent much time for that but now i have a big problem :
when one of tabs is activated the next tab and prev tab is loading too
and onCreated() method is called but i don't need that i need just
calling onCreated() method when switching to tabs
This is my project files
mainActivity.java
package info.androidhive.tabsswipe;
import info.androidhive.tabsswipe.adapter.TabsPagerAdapter;
import ir.zinoo.mankan.R;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.content.SharedPreferences;
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
#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().setTabListener(this));
}
actionBar.setStackedBackgroundDrawable(new ColorDrawable(Color.parseColor("#333333")));
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#333333")));
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) {
}
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);
}
}
tabPagerAdapter.java class
package info.androidhive.tabsswipe.adapter;
import info.androidhive.tabsswipe.BmiFragment;
import info.androidhive.tabsswipe.CaloriFragment;
import info.androidhive.tabsswipe.FatFragment;
import info.androidhive.tabsswipe.KamarFragment;
import info.androidhive.tabsswipe.OstokhanFragment;
import info.androidhive.tabsswipe.OtherFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new BmiFragment();
case 1:
// Games fragment activity
return new CaloriFragment();
case 2:
// Movies fragment activity
return new KamarFragment();
case 3:
// Movies fragment activity
return new OstokhanFragment();
case 4:
// Movies fragment activity
return new FatFragment();
case 5:
// Movies fragment activity
return new OtherFragment();
}
return null;
}
#Override
public int getCount() {
//get item count - equal to number of tabs
return 6;
}
}
Now My question is How to avoid calling on created method of other tabs when in switch to special tab?
From Android Documentation about FragmentPagerAdapter :
This version of the pager is best for use when there are a handful of typically more static fragments to be paged through, such as a set of tabs. The fragment of each page the user visits will be kept in memory, though its view hierarchy may be destroyed when not visible. This can result in using a significant amount of memory since fragment instances can hold on to an arbitrary amount of state. For larger sets of pages, consider FragmentStatePagerAdapter
FragmentStatePagerAdapter :
This version of the pager is more useful when there are a large number
of pages, working more like a list view. When pages are not visible to
the user, their entire fragment may be destroyed, only keeping the
saved state of that fragment. This allows the pager to hold on to much
less memory associated with each visited page as compared to
FragmentPagerAdapter at the cost of potentially more overhead when
switching between pages.
So, as you are using FragmentPagerAdapter, FrgmentManager will add all your fragment in memory while user is using app. Furthermore, when user switches to any page, FragmentManager loads previous and next page and it will call onCreate() of your tabs.
As you have now 6 tabs, may be you want to add more tabs, FragmentStatePagerAdapter is more suitable.
For checking exactly which fragment is visible to user, you can do something like this :
public class TabsPagerAdapter extends FragmentPagerAdapter {
/* declare fragment objects here globally */
BmiFragment mBmi = new BmiFragment();
CaloriFragment mCalori = new CaloriFragment();
KamarFragment mKamar = new KamarFragment();
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
mBmi.setUserVisibleHint(false);
return mBmi;
case 1:
// Games fragment activity
mCalori.setUserVisibleHint(false);
return mCalori;
case 2:
// Movies fragment activity
mKamar.setUserVisibleHint(false);
return mKamar;
/* like this for all case*/
}
return null;
}
}
Set onPageChangeListener to ViewPager from your Activity :
mPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// position tab is visible to user
switch(position) {
case 0 :
mBmi.setUserVisibleHint(true);
break;
/* like this for all case */
}
}
});
Override setUserVisibleHint() method in all fragments :
public class <Your_Fragment> extends Fragment {
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// do something, your fragment is visible
} else {
// your fragment is loaded, but not visible to user currently
}
}
}
Related
I want to start different activities depending on the click of the tab bar item but I get a blank page as started activity in the "windows class". What I intended to do is start different activities on click of tab bar item.
Tab Bar Activity Class
import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TabHost;
public class TabBar extends FragmentActivity {
ViewPager Tab;
TabPagerAdapter TabAdapter;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabbardefault);
try {
TabAdapter = new TabPagerAdapter(getSupportFragmentManager());
Tab = (ViewPager) findViewById(R.id.pager);
Tab.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar = getActionBar();
actionBar.setSelectedNavigationItem(position);
}
});
Tab.setAdapter(TabAdapter);
actionBar = getActionBar();
//Enable Tabs on Action Bar
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
catch (Exception e)
{
}
ActionBar.TabListener tabListener = new ActionBar.TabListener(){
#Override
public void onTabReselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
Tab.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
}};
//Add New Tab
actionBar.addTab(actionBar.newTab().setText("Home").setTabListener(tabListener));
actionBar.addTab(actionBar.newTab().setText("Celeb").setTabListener(tabListener));
actionBar.addTab(actionBar.newTab().setText("Videos").setTabListener(tabListener));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_tab_bar, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
TabPagerAdapter
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class TabPagerAdapter extends FragmentStatePagerAdapter {
public TabPagerAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
//Fragement for Android Tab
return new Android();
case 1:
//Fragment for Ios Tab
return new Ios();
case 2:
//Fragment for Windows Tab
return new Windows();
}
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 3; //No of Tabs
}
}
Windows
public class Windows extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View windows = inflater.inflate(R.layout.feed_main, container, false);
//((TextView)windows.findViewById(R.id.textView)).setText("Windows");
return windows;
}}
To answer you, you are not actually starting an Activity you a switching through Fragments, Fragment is just a Custom View, and you inflate an xml to represent the Custom View which is the Fragment, if you want to start an Activity after your Tab is selected then you call startActivity(Intent); startActivity(new Intent(classname.this,the_class_i_want_to_start.class));
and your Windows class extends Fragment it should be Activity if what you want is the functionality of Fragment then you aint got a problem
hope its lucid
I have created my project by using the built in Tabbed Activity in Android Studio, I have added 3 tabs and their respective Fragments in separate classes.
Then I tried to add an icon to each Tab, but faced some errors.
My MainActivity Code is the following:
package appetizers.com.myvault;
import java.util.Locale;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// code to hide the action bar
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
#Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position) {
case 0:
return new FragmentPassword();
case 1:
return new FragmentPicture();
case 2:
return new FragmentSettings();
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages.
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;
}
}
}
My Fragment code, where I am trying to add an Icon to the tab is the following:
package appetizers.com.myvault;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
public class FragmentPassword extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static FragmentPassword newInstance(int sectionNumber) {
FragmentPassword fragment = new FragmentPassword();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public FragmentPassword() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_password, container, false);
TabHost tabHost = (TabHost) getActivity().findViewById(android.R.id.tabhost);
View passwordTab = tabHost.getTabWidget().getChildAt(0);
ImageView tabTitleIcon = (ImageView) passwordTab.findViewById(android.R.id.icon);
tabTitleIcon.setImageResource(R.drawable.ic_launcher);
return rootView;
}
}
I used the Tab Host to try to get the Icon and display it in the tab, but it is not working.
Can someone guide me, step by step, on how to achieve this ?
Please note, that I have went through many tutorials and examples, but non of them were adding an icon to tabs, in a default Tabbed Activity, where the ActionBarActivity is extended and the ActionBar.TabListener is implemented, in the MainActivity, and the Fragment is in a seperate class.
Thank you in advance.
Make a list to hold icons, and set them following:
ArrayList<int> iconList = new ArrayList<>();
//then put your icons by `R.drawable.icon_name` ids to list
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this))
.setIcon(iconList.get(i));
}
You have to add the icons when you adding tabs to the action bar.
Try this,
actionBar.addTabactionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setIcon(getResources().getDrawable(R.drawable.ic_launcher)) // use what icon you need
.setTabListener(this));
I'm quite new to Android. I'm stuck with this issue for a few days now.
I'm using the new google's Template of Action bar Tab with swipe (ViewPager).
Inside each fragment, I want to display a dynamic list of cards (with cardslib : https://github.com/gabrielemariotti/cardslib). The data for the cards come from an asyncTask which is fetching data from an url.
This is my problem : When I launch the app, the first View is display, but the ViewPager prepare the view for the second page, so the async task for the second screen is launch too. And the cards of the second screen are added to the first one.
Then if i swipe to the second screen, nothing is displayed, and the async task for the third screen is launch. So if swipe to the thrid screen, nothing... And then if i switch again to the second screen, the cards with data of the first screen are displayed... A real mess !
I think I have a probleme with the onCreate, onCreateView, or something like that. Maybe the code is sometimes not at the right place.. I don't know. I tried a lot of small modofication, but nothing worked. (but it worked like this with just action bar tab and without the ViewPager).
Thanks
Here is my code :
import java.util.Locale;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v13.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a {#link FragmentPagerAdapter}
* derivative, which will keep every loaded fragment in memory. If this
* becomes too memory intensive, it may be best to switch to a
* {#link android.support.v13.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mSectionsPagerAdapter.notifyDataSetChanged();
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
//mSectionsPagerAdapter.notifyDataSetChanged();
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
mSectionsPagerAdapter.notifyDataSetChanged();
}
#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 onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
if(tab.getPosition() != mViewPager.getCurrentItem()) {
mViewPager.setCurrentItem(tab.getPosition());
}
// mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
mSectionsPagerAdapter.notifyDataSetChanged();
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
mSectionsPagerAdapter.notifyDataSetChanged();
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
// Show 3 total pages.
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;
}
}
}
And here is the Fragment
import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.CardArrayAdapter;
import it.gmariotti.cardslib.library.internal.CardHeader;
import it.gmariotti.cardslib.library.view.CardListView;
import java.util.ArrayList;
import java.util.List;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.example.webanajones.asyncTask.GetItemTask;
import com.example.webanajones.asyncTask.IResultsListener;
import com.example.webanajones.asyncTaskResponse.ItemJsonResponse;
import com.example.webanajones.asyncTaskResponse.ItemJsonResponse.Item;
/**
* A placeholder fragment containing a simple view.
*/
public class PlaceholderFragment extends Fragment implements
IResultsListener {
/**
* The fragment argument representing the section number for this
* fragment.
*/
static final String ARG_SECTION_NUMBER = "section_number";
public static int limit = 0;
IResultsListener listener = this;
ArrayList<Card> cards = new ArrayList<Card>();
CardArrayAdapter mCardArrayAdapter;
int flag = 0;
boolean loadMore = true;
CardListView listView;
private int idx;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Bundle data = getArguments();
// idx = data.getInt("idx") +1;
limit = 0;
flag = 0;
loadMore = true;
List<String> params = new ArrayList();
params.add(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
params.add(String.valueOf(limit));
GetItemTask getItemTask = new GetItemTask();
getItemTask.setOnResultsListener(listener);
getItemTask.execute(params);
}
/**
* Returns a new instance of this fragment for the given section number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#SuppressWarnings("unchecked")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
#Override
public void onGetItemTaskSucceeded(ItemJsonResponse itemJsonResponse) {
if (mCardArrayAdapter != null) {
mCardArrayAdapter.notifyDataSetChanged();
}
if (itemJsonResponse.getSuccess() != 0) {
loadMore = true;
final Item[] itemTable = itemJsonResponse.getItemArray();
for (int itemIndex = 0; itemIndex < itemTable.length; itemIndex++) {
if (itemTable[itemIndex].getTypeId() == 2) { // 2 = type GIF
final int index = itemIndex;
Card gifCard = new CardGif(getActivity()){
#Override
public void setupInnerViewElements(ViewGroup parent, View view) {
DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
int width = (int) (metrics.widthPixels * 0.97);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, LinearLayout.LayoutParams.WRAP_CONTENT);
params.bottomMargin = 30;
LinearLayout LinearLayout = (LinearLayout) parent.findViewById(R.id.inner_frame);
GIFWebView gifView = new GIFWebView (getActivity(), itemTable[index].getObjectUrl());
LinearLayout.addView(gifView);
}
};
CardHeader header = new CardHeader(getActivity());
header.setTitle(itemTable[itemIndex].getTitle());
cards.add(gifCard);
}
if (itemTable[itemIndex].getTypeId() == 1) { // 1 = image
Card card = new Card(getActivity());
CardHeader header = new CardHeader(getActivity());
header.setTitle(itemTable[itemIndex].getTitle());
card.addCardHeader(header);
MyThumbnail thumb = new MyThumbnail(getActivity(), itemTable[itemIndex].getObjectUrl());
thumb.setExternalUsage(true);
card.addCardThumbnail(thumb);
final int index = itemIndex;
card.addPartialOnClickListener(Card.CLICK_LISTENER_THUMBNAIL_VIEW, new Card.OnCardClickListener() {
#Override
public void onClick(Card card, View view) {
Intent intent = new Intent(getActivity(), FullscreenActivity.class);
intent.putExtra("imageUrl", itemTable[index].getObjectUrl());
startActivity(intent);
}
});
cards.add(card);
}
}
if (flag == 0) {
mCardArrayAdapter = new CardArrayAdapter(getActivity(), cards);
listView = (CardListView) getActivity().findViewById(
R.id.carddemo_list);
listView.setAdapter(mCardArrayAdapter);
flag = 1;
}
}
else {
loadMore = false;
}
loadMoreCards(mCardArrayAdapter, loadMore);
}
public void loadMoreCards(CardArrayAdapter mCardArrayAdapter, boolean loadMore) {
if (listView != null) {
mCardArrayAdapter.notifyDataSetChanged();
if (loadMore) {
listView.setOnScrollListener(new EndlessScrollListener() {
#Override
public void onLoadMore(int page, int totalItemsCount) {
limit += 5;
List<String> params = new ArrayList();
params.add("1");
params.add(String.valueOf(limit));
GetItemTask getItemTask = new GetItemTask();
getItemTask.setOnResultsListener(listener);
getItemTask.execute(params);
}
});
}
}
}
//fin placeholderfrag
#Override
public void onGetImageTaskSucceeded(Bitmap bitmap) {
// TODO Auto-generated method stub
}
}
Thanks #GabrieleMariotti, it helped ! In fact I already tried to use different classes for the different fragments, but I forget to give diferent IDs to my cardsLists. It solved the problem. Btw, good job for your lib, it is awesome.
So for the next one : create differents classes for all your differents fragments. They have to use differents layout, and the cardsList have to use differents ID.
I essentially copy pasted the activity that implements the swiper. The code that I added is the test increment. This is what happens:
App starts (I'm swiping left and right:
Section 1: 1
Section 2: 1
Seciton 3: 1 (everything is good up to bere)
Section 2: 1 (why wasn't this 2, it increments)
Section 1: 2
Section 2: 1 (again, it's 1)
Section 3: 2
Section 2: 1
Section 1: 3
Section 2: 1
Section 3: 3
The way the numbers increment are not making sense. I landed on section 2 several times, the test class attribute should have incremented but did not. What's going on?
package activities;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v13.app.FragmentPagerAdapter;
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.TextView;
import com.comp.chat.R;
import java.util.Locale;
public class SplashActivity extends Activity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v13.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
//For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.splash, 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 onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
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;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
private int test = 0;
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_splash, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
//textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
textView.setText(Integer.toString(++test));
return rootView;
}
}
}
Ok it's quite easy. In viewPager you have views stored in memory. Current selected, one on left, one on right. If you swipe from 3->2 than Section 2, has already created view, so it doesn't need to create it again, thus test stays at same value. Than if you swipe to get section 1, than it's recreated from scratch, and test number is 1.
Check this out: http://developer.android.com/reference/android/support/v4/view/ViewPager.html#setOffscreenPageLimit(int)
It's probably way too early for me to ask this, since I'm totally new to programming altogether, but here goes.
Using the "Fixed Tabs + Swipe" navigation for 2 tabs on the main activity of a new project in Eclipse (Kepler), how could one make it that when launched, the app will be on a '3rd tab' that is basically the 2 tabs being simultaneously activate, incorporating the items of both tabs in one list?
The idea is to have each tab be a category of a grid of items, that can be combined in this 'merged' tab, then one can swipe from right to left to select one tab with one category, swipe again to switch to the next category, then swipe a 3rd time (in the same direction) to return to the screen with both merged (and basically have a loop like that when swiping in that one direction).
The swiping between tabs is only meant to occur in one direction, while a swipe in the other, will bring up a set of options instead.
The items themselves will also be further subdivided on each page in expandable lists, which will be identical in both tabs, allowing them to merge.
The 'merged tab' would also have title text that 'overlays' the 2 category tabs and indicates their combined state.
Here is my code in MainActivity.java so far, where I kind of want section 1 to be a combination of section 2 and 3:
import java.util.Locale;
import android.app.ActionBar;
import android.app.FragmentTransaction;
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.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#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 void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
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;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,
container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return rootView;
}
}
}
Any help rendered will be greatly appreciated; thanks in advance, everyone.