I am developing an application for on-line shopping. Due to the big number of products that I have to display I have used a lot of categorization. One of the main feature that I am using is ViewPager with PageAdapter. In every fragment it's supposed to be different layouts. In one of the fragments I have used a GridView. The problem is that when I switch between pages, and I return to the first page the size of the GridView , the number of elements inside keeps growing repeating themselves. For example if I have 12 elements at the beginning, after I switch pages and then get back again it becomes 24, 36 etc.
Below is the code I used for this:
EbuyHomeScreen.class
public class EbuyHomeScreen extends FragmentActivity {
#SuppressLint("InlinedApi") protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ebuy_home_screen);
/** Getting a reference to the ViewPager defined the layout file */
ViewPager pager = (ViewPager) findViewById(R.id.pager);
/** Getting fragment manager */
FragmentManager fm = getSupportFragmentManager();
/** Instantiating FragmentPagerAdapter */
EbuyFragmentPagerAdapter pagerAdapter = new EbuyFragmentPagerAdapter(fm);
/** Setting the pagerAdapter to the pager object */
pager.setAdapter(pagerAdapter);
}
EbuyFragmentPagerAdapter.class
public class EbuyFragmentPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 3;
/** Constructor of the class */
public EbuyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
/** This method will be invoked when a page is requested to create */
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
EbuyFragmentLatest myFragmentLatest = new EbuyFragmentLatest();
return myFragmentLatest;
case 1:
EbuyFragmentSold myFragmentSold = new EbuyFragmentSold();
return myFragmentSold;
case 2:
EbuyFragmentSponsored myFragmentSponsored = new EbuyFragmentSponsored();
return myFragmentSponsored;
default:
EbuyFragmentLatest myFragmentLatestDefault = new EbuyFragmentLatest();
return myFragmentLatestDefault;
}
}
/** Returns the number of pages */
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
/** code for returning the title*/ }
}
}
EbuyFragmentLatest.class
public class EbuyFragmentLatest extends Fragment {
final ArrayList<EbuyItem> ebuy_data = new ArrayList<EbuyItem>();
private EbuyItemAdapter customAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.ebuy_home_fragment_latest,
container, false);
JazzyGridView mGrid = (JazzyGridView)v.findViewById(R.id.ebuy_list);
mGrid.setTransitionEffect(JazzyHelper.TILT);
ebuy_data.add(new EbuyItem("http://www.ebuy.al/Images/dsc/8884_400_300.jpg","Fustan Glamour","2,500L [17.9 €]"));
/*
** filing with data continues */
customAdapter = new EbuyItemAdapter(
container.getContext(), ebuy_data);
mGrid.setAdapter(customAdapter);
return v;
}
}
And this is the last class EbuyItemAdapter.class
public class EbuyItemAdapter extends BaseAdapter {
private ArrayList<EbuyItem> ebuy_data;
private LayoutInflater layoutInflater;
public EbuyItemAdapter(Context context, ArrayList<EbuyItem> ebuy_data) {
this.ebuy_data = ebuy_data;
layoutInflater = LayoutInflater.from(context);
}
public int getCount() {
return ebuy_data.size();
}
public Object getItem(int position) {
return ebuy_data.get(position);
}
public long getItemId(int position) {
return position;
}
#SuppressLint({ "DefaultLocale", "InflateParams" })
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.ebuy_item, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.price = (TextView) convertView.findViewById(R.id.price);
holder.image = (ImageView) convertView
.findViewById(R.id.ebuy_image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(((EbuyItem) ebuy_data.get(position)).getName());
holder.price.setText(((EbuyItem) ebuy_data.get(position)).getPrice());
UrlImageViewHelper.setUrlDrawable(holder.image,
((EbuyItem) ebuy_data.get(position)).getImageUrl(),
R.drawable.loading);
return convertView;
}
static class ViewHolder {
TextView name;
TextView price;
ImageView image;
}
}
Related
i'm trying to put ViewPager into ListView
here the code of ListView AdapterClass:
public class AdapterPager extends BaseAdapter {
.....
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.component_pager, parent, false);
new ViewHolder(view, itemData.get(position));
}
return view;
}
View Holder:
private class ViewHolder {
ViewPager pager;
PagerAdapter pagerAdapter;
public ViewHolder(View view, ModelItem model){
pager = (ViewPager) view.findViewById(R.id.pager);
pager.setId(model.getId()); /// uniq ID
pagerAdapter = new MyFragmentPagerAdapter(((FragmentActivity)view.getContext()).getSupportFragmentManager());
pager.setAdapter(pagerAdapter);
}
then, Pager Adapter:
static final int PAGE_COUNT = 2;
private class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return FragmentComponentPager.newInstance(position, mModel);
}
#Override
public float getPageWidth(int position) {
float f_width = 1f;
return f_width;
}
#Override
public int getCount() {
return PAGE_COUNT;
}
}
and, the last, Pager Fragment:
public class FragmentComponentPager extends Fragment {
static final String ARGUMENT_PAGE_NUMBER = "arg_page_number";
static final String ARGUMENT_NAME = "arg_name";
int pageNumber;
public static FragmentComponentPager newInstance(int page, ModelItem data) {
FragmentComponentPager pageFragment = new FragmentComponentPager();
Bundle arguments = new Bundle();
arguments.putInt(ARGUMENT_PAGE_NUMBER, page);
if (data != null){
arguments.putString(ARGUMENT_NAME, data.getName());
}
pageFragment.setArguments(arguments);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageNumber = getArguments().getInt(ARGUMENT_PAGE_NUMBER);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.component_list, null);
TextView tvTitle = (TextView) view.findViewById(R.id.tvTitle);
tvTitle.setText(getArguments().getString(ARGUMENT_NAME));
return view;
}
}
when i run it ListView shows all items that i've added, but all of them, except the last one, with empty ViewPager.
and, if i removed pager.setId(model.getId()); the first item shows view pager, and the others empty.
guess that smth wrong with FragmentManager, but have no idea how deal with it :(
In your ViewHolder you need to call getChildFragmentManager instead of getSupportFragmentManager.
I have in my fragment (called "buy") a listview. So of course I have a adapter. The problem is that I have a math process in my adapter and I need the result will be sent to my txtview. But unfortunatly my textview is in my fragment. So How can I send this variable? some like
((FragmentBuy) Fragment).send(prize);
But of course this doesn't work. Thanks for helping!
I have a MainActivity
public class MainActiviry extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabs);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Buy"));
tabLayout.addTab(tabLayout.newTab().setText("Sell"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
And of course my pager
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
FragmentCompras tab1 = new FragmentBuy();
return tab1;
case 1:
FragmentDespensa tab2 = new FragmentSell();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
My adapter
public class ListViewAdapter extends BaseAdapter{
public ArrayList<HashMap<String, String>> list;
Activity activity;
int contador = 0;
public ListViewAdapter(Activity activity, ArrayList<HashMap<String, String>> list){
super();
this.activity = activity;
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
private class ViewHolder {
TextView name;
TextView marc, cant, prec;}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null){
convertView = inflater.inflate(R.layout.list_colum, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.marc = (TextView) convertView.findViewById(R.id.marc);
holder.cant = (TextView) convertView.findViewById(R.id.cant);
holder.prec = (TextView) convertView.findViewById(R.id.prec);
convertView.setTag(holder);
}
else{
holder=(ViewHolder) convertView.getTag();
}
HashMap<String, String> map = list.get(position);
holder.name.setText(map.get(FIRST_COLUMN));
holder.marc.setText(map.get(SECOND_COLUMN));
holder.prec.setText(map.get(THIRD_COLUMN));
holder.cant.setText(map.get(FOURTH_COLUMN));
return convertView;
}
And my fragment
public class FragmentBuy extends android.support.v4.app.Fragment implements View.OnClickListener{
private ArrayList<HashMap<String, String>> list;
//HashMap<String, String> temp = new HashMap<String, String>();
private Button scanBtn;
static boolean guardar;
private TextView txttotal, formatTxt, contentTxt, lblmx, textView, cantidadproducto;
ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activy_micompra, container, false);
final DbHelper admin = new DbHelper(view.getContext(), null);
list = new ArrayList<HashMap<String, String>>();
setHasOptionsMenu(true);
guardar = false;
txttotal = (TextView)view.findViewById(R.id.total); //this is my textview
textView = (TextView) view.findViewById(R.id.mxcompra);
cantidadproducto = (TextView)view.findViewById(R.id.cantidadproducto);
return view;
}
So a straight forward approach will be creating a variable for your math calculation directly in your Activity. So here are the steps:
Create an interface callback which sends the data to your activity from the ListAdapter
Create instance variable for your fragment which holds public method send(prize) in your MainActivity
Call your method directly from the activity by fragmentBuy.send(prize) in the callback of the interface
You can go with Event bus to communicate back to fragment from your adapter class.It simplifies the communication between components.It also performs well with Activities, Fragments, and background threads.For simple communication process you can go with Otto Event Bus..
For more detail , you can go here.. Otto event bus
You can communicate between Listview adapter and Fragment using interface.
Steps:
1.Create an interface with send method.
2.Implement that method in your Fragment.
3. While crating adapter pass a reference of Interface(i.e interface implementing class.. which is current fragment.)
4) In adapter using that Interface object call send method.
i have a fragment which uses AsyncTask to download the JSON and display several NEWS segments. Here i can slide up and down and view all the News segments. But i want to slide this horizontally and view the news segments one by one by sliding. As far as i know (i'm a beginner) i have to use a ViewPager adapter to achive this.But i don't know how.Please someone help me.
My fragment class
public class NewsDetailFragment extends Fragment {
private View view1;
private ArrayList<BaseElement> newsdetail;
private LazyAdapter adapter;
private Activity activity;
private CommonVariable commonVariable;
private ProgressDialog dialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.newsdetail_fragment, container,
false);
activity = this.getActivity();
commonVariable = (CommonVariable) activity.getApplication();
view1 = (View) view.findViewById(R.id.list);
dialog = new ProgressDialog(NewsDetailFragment.this.getActivity());
dialog.setMessage("Loading News");
dialog.setCancelable(true);
new BackGround().execute();
return view;
}
public class BackGround extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
newsdetail = JSONServices.getNewsDescription();
return null;
}
#SuppressWarnings("unchecked")
#Override
/* check again */
protected void onPostExecute(Void result) {
commonVariable.setTheater(newsdetail);
adapter = new LazyAdapter(newsdetail, activity,Element.NEWS_DETAIL.getType());
((AdapterView<ListAdapter>) view1).setAdapter(adapter);
dialog.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog.show();
super.onPreExecute();
}
}
}
My ViewPager adapter
public class ViewPageAdapter extends PagerAdapter {
private LinkedHashMap<String, BaseElement> item;
private int page;
private Activity activity;
private LayoutInflater inflater;
private ViewPageAdapter(LinkedHashMap<String, BaseElement> item, int page,
Activity activity) {
super();
this.item = item;
this.page = page;
this.activity = activity;
}
#Override
public int getCount() {
return item.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
// TODO Auto-generated method stub
return view == (LinearLayout) object;
}
#Override
public Object instantiateItem(View container, int position) {
View view = null;
return view;
}
}
PageAdapter
public class PageAdapter extends FragmentStatePagerAdapter {
public static final String ARG_SECTION_NUMBER = "section_number";
private ArrayList<BaseElement> item;
private Activity activity;
public PageAdapter(FragmentManager fragmentManager,
ArrayList<BaseElement> item, Activity activity) {
super(fragmentManager);
this.activity = activity;
this.item = item;
}
#Override
public Fragment getItem(int position) {
// ------set fragment class for viewPager----------//
Fragment fragment = new PageSectionFragment();
Bundle bundle = new Bundle();
// ---- setPage position as agument for PageSectionFragment
// class---//
bundle.putInt(ARG_SECTION_NUMBER, position);
fragment.setArguments(bundle);
return fragment;
}
#Override
public int getCount() {
return item.size();
}
#Override
public int getItemPosition(Object object) {
return PagerAdapter.POSITION_NONE;
}
#Override
public CharSequence getPageTitle(int position) {
FilmCategory film = (FilmCategory) item.get(position);
Sihala sinhla = new Sihala(activity);
return sinhla.getSinhalaString(film.getCategory());
}
}
Add this into your layout..
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:overScrollMode="never" />
Then Add this class into your Fragment class.
private class ScreenSlidePagerAdapter extends FragmentPagerAdapter {
private SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
/*#Override
public android.support.v4.app.Fragment getItem(int position) {
return AlertSlideFragment.create(position);
}*/
#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.
tabFragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position);
tabFragment.setArguments(args);
/*fragment = getRegisteredFragment(0);*/
return tabFragment;
}
#Override
public int getCount() {
return NUM_PAGES;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container,
position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
Finally here is the DummySectionFragment
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 = null;
/*View rootView = inflater.inflate(R.layout.fragment_tabbed_dummy,
container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));*/
int screenNum = getArguments().getInt(ARG_SECTION_NUMBER);
//listAdapterAlert= new ListAdapterAlert(getActivity(), R.layout.alert_list);
if(screenNum == 0) // 0 for recent
{
rootView = inflater.inflate(R.layout.alert_list,
container, false);
TextView tv = (TextView) rootView.findViewById(R.id.tv);
}
else if(screenNum == 1) // 1 for by due date
{
rootView = inflater.inflate(R.layout.alert_list,
container, false);
TextView tv = (TextView) rootView.findViewById(R.id.tv);
}
else if(screenNum == 2) // 2 for by campaign
{
rootView = inflater.inflate(R.layout.campaign_alert,
container, false);
}
return rootView;
}
}
Hope it will help you.
I created a swipe tab view inside a fragment. I tested this in a FragmentActivity with no issues. I tested with pages that consisted of different fragment classes and fragments all from the same class... again no issues.
Then, I changed the FragmentActivity to a Fragment. I tested again with different Fragment classes representing each page and had no problem. Finally, i repeated the test with fragments of the same class and ran into issues.
There are 3 pages right now representing three weeks. At first week 1 shows up. I swipe to week 2 and there is nothing. I swipe to week 3 and nothing again. When I swipe back to week 1, the only viewable page ends up being the middle page. Is this an issue with fragment life cycles? I'm not sure how to debug this special circumstance. I'm looking for possible causes so I can start solving this issue.
public class WeeklyScrollTab extends Fragment {
private ViewPager my_view_pager;
private View my_layout;
private int my_current_page;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
my_layout = inflater.inflate(R.layout.weekly_scroll_tabs, container, false);
return my_layout;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Getting the arguments to the Bundle object */
//Bundle data = getArguments();
/** Getting integer data of the key current_page from the bundle */
//my_current_page = data.getInt("week_val", 0);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
my_view_pager = (ViewPager)my_layout.findViewById(R.id.week_list_pager);
FragmentManager manager = getActivity().getSupportFragmentManager();
//FragmentManager manager = getChildFragmentManager();
my_view_pager.setAdapter(new WeeklyScrollAdapter(manager));
super.onActivityCreated(savedInstanceState);
}
public int getCurrentPage(){
return my_current_page;
}
public class WeeklyScrollAdapter extends FragmentStatePagerAdapter {
public WeeklyScrollAdapter(FragmentManager the_manager){
super(the_manager);
}
#Override
public Fragment getItem(int the_position) {
Fragment fragment1 = null;
if(the_position == 0){
fragment1 = new MyNflPlayerList();
Bundle args1 = new Bundle();
args1.putInt("week_val"+the_position, the_position);
fragment1.setArguments(args1);
}
if(the_position == 1){
fragment1 = new MyNflPlayerList();
Bundle args2 = new Bundle();
args2.putInt("week_val"+the_position, the_position);
fragment1.setArguments(args2);
}
if(the_position == 2){
fragment1 = new MyNflPlayerList();
Bundle args3 = new Bundle();
args3.putInt("week_val"+the_position, the_position);
fragment1.setArguments(args3);
}
return fragment1;
}
/**
*
* #return number of total pages
*/
#Override
public int getCount() {
return 3;
}
/**
* gets title for tab
*/
#Override
public CharSequence getPageTitle(int position) {
if(position ==0){
return "Week 1";
}
if(position == 1){
return "Week 2";
}
if(position == 2){
return "Week 3";
}
return super.getPageTitle(position);
}
public class NflPlayerAdapter extends BaseAdapter {
private ArrayList<NflPlayerModel> my_list;
private Context my_context;
public NflPlayerAdapter(Context c){
my_context = c;
my_list = new ArrayList<NflPlayerModel>();
my_list.add(new NflPlayerModel("T.","Brady","NE","QB",56));
my_list.add(new NflPlayerModel("A.","Peterson","MN","RB",24));
my_list.add(new NflPlayerModel("D.","Bryant","DAL","WR",18));
my_list.add(new NflPlayerModel("M.","Gattica","TB","K",9));
}
#Override
public int getCount() {
return my_list.size();
}
#Override
public NflPlayerModel getItem(int i) {
return my_list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//getting the data and injecting it into the each row view
View row = convertView;
NflPlayerHolder holder = null;
if(row == null){
LayoutInflater inflater = (LayoutInflater)my_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.my_nfl_player_row,parent, false);
holder = new NflPlayerHolder(row);
row.setTag(holder);
}
else{
holder = (NflPlayerHolder) row.getTag();
}
NflPlayerModel temp = my_list.get(position);
holder.getFname().setText(temp.getFname());
holder.getLname().setText(temp.getLname());
holder.getTeam().setText(temp.getTeam());
holder.getPosition().setText(temp.getPosition());
holder.getPoints().setText(Integer.toString(temp.getPoints()));
return row;
}
class NflPlayerHolder {
/**
* TextView object in my_league_row xml.
*/
private TextView my_fname;
private TextView my_lname;
private TextView my_team;
private TextView my_position;
private TextView my_points;
/**
* Constructor. Converts the xml txt_league_name to Java object.
* #param v
*/
public NflPlayerHolder(View v){
my_fname = (TextView)v.findViewById(R.id.player_fname);
my_lname = (TextView)v.findViewById(R.id.player_lname);
my_team = (TextView)v.findViewById(R.id.player_team);
my_position = (TextView)v.findViewById(R.id.player_position);
my_points = (TextView)v.findViewById(R.id.player_points);
}
public TextView getFname(){
return my_fname;
}
public TextView getLname(){
return my_lname;
}
public TextView getTeam(){
return my_team;
}
public TextView getPosition(){
return my_position;
}
public TextView getPoints(){
return my_points;
}
public class MyNflPlayerList extends Fragment implements AdapterView.OnItemClickListener{
private View my_layout;
private ListView my_list_view;
private static HomeActivityCommunicator my_communicator;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
my_layout = inflater.inflate(R.layout.my_nfl_player_list, container, false);
return my_layout;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
my_list_view = (ListView)getActivity().findViewById(R.id.nfl_player_list_view);
NflPlayerAdapter adapter = new NflPlayerAdapter(getActivity());
my_list_view.setAdapter(adapter);
my_list_view.setOnItemClickListener(this);
super.onActivityCreated(savedInstanceState);
}
public void setHomeActivityCommunicator(HomeActivityCommunicator the_communicator){
my_communicator = the_communicator;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.e("mike", "the player index is " + i);
my_communicator.onMyNflPlayerListSelection(i);
}
I have a FragmentActivity that uses a ViewPager to flip left and right through pages of data (two ListFragments).
public class StopsActivity extends FragmentActivity {
private ViewPager mViewPager;
private PagerTabStrip mPagerTabStrip;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stops);
mPagerTabStrip =(PagerTabStrip)findViewById(R.id.pager_header);
mViewPager = (ViewPager)findViewById(R.id.pager);
mPagerTabStrip.setDrawFullUnderline(true);
mPagerTabStrip.setTabIndicatorColorResource(R.color.pagerTabStrip);
mViewPager.setAdapter(new StopsAdapter(getSupportFragmentManager()));
mViewPager.setCurrentItem(0);
}
private class StopsAdapter extends FragmentPagerAdapter {
public StopsAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return StopsFragment.newInstance(routename, Stop.FORWARD);
case 1:
return StopsFragment.newInstance(routename, Stop.BACKWARD);
}
return null;
}
#Override
public int getCount() { return 2;}
#Override
public CharSequence getPageTitle(int position) { /* implementation ... */}
}
}
Everything runs ok, but I think that the instantation of the second StopFragment invalidate the data of the first one when getItem is called.
public class StopsFragment extends ListFragment {
private StopsAdapter mStopsAdapter;
private ListView mListView;
private String routename;
private int direction;
public static StopsFragment newInstance(String routename, int direction) {
StopsFragment stopsFragment = new StopsFragment();
// Supply arguments
Bundle args = new Bundle();
args.putString("routename", routename);
args.putInt("direction", direction);
stopsFragment.setArguments(args);
return stopsFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Setup the adapter
ArrayList<Stop> stops = ...
mStopsAdapter = new StopsAdapter(getActivity(), stops);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle inState) {
View rootView = inflater.inflate(R.layout.fragment_stops, container, false);
// Attach the adapter
mListView = (ListView) rootView.findViewById(android.R.id.list);
mListView.setAdapter(mStopsAdapter);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
The page "IDA" corresponds to StopFragment with argument Stop.FORWARD and the page "VUELTA" corresponds the StopFragment with argument Stop.BACKWARD. As you can see in the images below, just one of them (the last one instantiate) is populated:
What I'm doing wrong?
EDIT
This is StopsAdapter
class StopsAdapter extends BaseAdapter {
private ArrayList<Stop> stops;
private LayoutInflater inflater;
public StopsAdapter(Context context, ArrayList<Stop> stops) {
this.stops = stops;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return stops.size();
}
#Override
public Object getItem(int position) {
return stops.get(position);
}
#Override
public long getItemId(int position) {
return (long)position;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_stop, parent, false);
}
TextView name = (TextView)convertView.findViewById(R.id.tvStopName);
TextView description = (TextView)convertView.findViewById(R.id.tvStopDescription);
Stop stop = (Stop)getItem(position);
name.setText(stop.name);
if (stop.info != null) {
description.setText(stop.info);
}
return convertView;
}
}
Ok, my fault. The code that was giving me problems is the only that I haven't posted (ArrayList<Stop> stops = ...). The code about Fragments and ViewPager works correctly.