How to set different size in Glide PreloadSizeProvider? - android-glide

I am using Glide to show images fetch from Firebase to show in RecyclerView in my Android App with the help of Glide PreloadSizeProvider as given in the documentation -
https://muyangmin.github.io/glide/int/recyclerview.html
But my image size is not fixed. The size is stored in a real-time database. So I need to change the
PreloadSizeProvider size. But I am unable to do that. My image size comes from the Firebase Realtime Database. So I can only set the PreloadSizeProvider after the data is loaded. How can I set different PreloadSizeProvider?
My current code
public class HomeFragment extends Fragment {
private DatabaseReference databaseReference;
private FirebaseUser mUser;
private final List<InfoModel> infoModelList = new ArrayList<>();
private InfoAdapter infoAdapter;
public HomeFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
RecyclerView infoRecyclerView = view.findViewById(R.id.frag_home_info_rec_view_id);
databaseReference = FirebaseDatabase.getInstance().getReference();
mUser = FirebaseAuth.getInstance().getCurrentUser();
Point size = new Point();
WindowManager windowManager = getActivity().getWindowManager();
windowManager.getDefaultDisplay().getSize(size);
screenWidth = size.x;
int screeHeight = size.y;
ListPreloader.PreloadSizeProvider sizeProvider = new FixedPreloadSizeProvider(1024, 768);
ListPreloader.PreloadModelProvider modelProvider = new MyPreloadModelProvider();
RecyclerViewPreloader<ContactsContract.CommonDataKinds.Photo> preloader = new RecyclerViewPreloader<>(Glide.with(this), modelProvider, sizeProvider, 10 );
infoRecyclerView.addOnScrollListener(preloader);
infoAdapter = new InfoAdapter(getActivity(), infoModelList);
infoAdapter.setScreenSize(screenWidth, screeHeight);
infoRecyclerView.setLayoutManager( new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
infoRecyclerView.setAdapter(infoAdapter);
infoRecyclerView.setHasFixedSize(false);
Query infoQuery = databaseReference.child("Data").child("Info").child("Home").child("Info").orderByChild("orderKey");
infoQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot ds) {
if(ds.exists()){
for(DataSnapshot dataSnapshot: ds.getChildren()){
InfoModel infoModel = dataSnapshot.getValue(InfoModel.class);
infoModelList.add(infoModel);
}
infoAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return view;
}
/*-------------------------------------------------------------------------------------------*/
private class MyPreloadModelProvider implements ListPreloader.PreloadModelProvider {
#NonNull
#Override
public List getPreloadItems(int position) {
String url = infoModelList.get(position).getImageUrl();
if (TextUtils.isEmpty(url)) {
return Collections.emptyList();
}
return Collections.singletonList(url);
}
#Nullable
#Override
public RequestBuilder<?> getPreloadRequestBuilder(#NonNull Object item) {
return Glide.with(HomeFragment.this).load((String) item) .override(1024, 768);
}
}
/*-------------------------------------------------------------------------------------------*/
}

Related

Android Studio FirestoreRecyclerAdapter Comment with Replies (nested recyclerview)

I wanted to make a Comment & Reply function for social media app
something like instagram
enter image description here
is there a way to have a nested recyclerview by using FirestoreRecyclerAdapter?
here is my plan
enter image description here
and here is the structure of my FirestoreRecyclerAdapter
homeRecycler = findViewById(R.id.homeRecycler);
linearLayoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
homeRecycler.setLayoutManager(linearLayoutManager);
homeRecycler.setItemAnimator(null);
StorageReference profileRef = storageReference.child("ProfileImage/"+fAuth.getCurrentUser().getUid()+"/profile.jpg");
profileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.get().load(uri).into(prof_img);
}
});
Query query = fStore.collection("Post")
.orderBy("homePostDate", Query.Direction.DESCENDING)
.limit(50);
FirestoreRecyclerOptions<HomeModel> options = new FirestoreRecyclerOptions.Builder<HomeModel>()
.setQuery(query, HomeModel.class)
.build();
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onRefresh() {
adapter.notifyDataSetChanged();
swipeRefresh.setRefreshing(false);
}
});
adapter = new FirestoreRecyclerAdapter<HomeModel, ViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ViewHolder holder, int position, #NonNull HomeModel model) {
holder.bind(model);
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup group, int i) {
View view = LayoutInflater.from(group.getContext())
.inflate(R.layout.home_each, group,false);
return new ViewHolder(view);
}
};
homeRecycler.setAdapter(adapter);
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView author, title, body, authorUid, docId, timestamp, upvotecount, downvotecount;
Button addcoment;
ToggleButton upvote, downvote;
ImageView prof_img;
HomeModel model;
RecyclerView replyRecycler;
public ViewHolder(#NonNull View itemView) {...}
public void bind(HomeModel homeModel) {...}
edit:
I tried just duplicating everything within the firestorerecycleradapter viewholder but couldnt make it work and dont even know if this is the proper way..
commentRecycler = findViewById(R.id.commentRecycler);
linearLayoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
commentRecycler.setLayoutManager(linearLayoutManager);
commentRecycler.setItemAnimator(null);
Query query = fStore.collection("Post")
.document(pdocId.getText().toString()).collection("comment")
.orderBy("commentPostDate", Query.Direction.DESCENDING)
.limit(50);
FirestoreRecyclerOptions<CommentModel> options = new FirestoreRecyclerOptions.Builder<CommentModel>()
.setQuery(query, CommentModel.class)
.build();
adapter = new FirestoreRecyclerAdapter<CommentModel, ViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ViewHolder holder, int position, #NonNull CommentModel model) {
holder.bind(model);
linearLayoutManager2 = new LinearLayoutManager(HomeView.this, RecyclerView.VERTICAL, false);
holder.replyRecycler.setLayoutManager(linearLayoutManager2);
holder.replyRecycler.setItemAnimator(null);
Query query2 = fStore.collection("Post")
.document(pdocId.getText().toString()).collection("comment")
.document(model.docId).collection("reply")
.orderBy("commentPostDate", Query.Direction.DESCENDING)
.limit(50);
FirestoreRecyclerOptions<ReplyModel> options2 = new FirestoreRecyclerOptions.Builder<ReplyModel>()
.setQuery(query2, ReplyModel.class)
.build();
adapter2 = new FirestoreRecyclerAdapter<ReplyModel, ViewHolder2>(options2) {
#Override
protected void onBindViewHolder(#NonNull ViewHolder2 holder, int position, #NonNull ReplyModel model) {
holder.bind(model);
Toast.makeText(HomeView.this, "this is test", Toast.LENGTH_SHORT).show();
}
#NonNull
#Override
public ViewHolder2 onCreateViewHolder(#NonNull ViewGroup group, int i) {
View view = LayoutInflater.from(group.getContext())
.inflate(R.layout.comment_each, group,false);
return new ViewHolder2(view);
}
};
holder.replyRecycler.setAdapter(adapter2);
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup group, int i) {
View view = LayoutInflater.from(group.getContext())
.inflate(R.layout.comment_each, group,false);
return new ViewHolder(view);
}
};
commentRecycler.setAdapter(adapter);
and then added another viewholder class
class ViewHolder extends RecyclerView.ViewHolder{
TextView author, body, authorUid, docId, timestamp, pReply, upvotecount, downvotecount;
TextInputLayout tilpReply;
ImageView prof_img;
Chip replyChip;
ToggleButton upvote, downvote;
ToggleButton replypop;
Button replyBtn;
CommentModel model;
RecyclerView replyRecycler;
public ViewHolder(#NonNull View itemView){...}
public void bind(CommentModel commentModel){...}
}
class ViewHolder2 extends RecyclerView.ViewHolder{
TextView author, body, authorUid, docId, timestamp, pReply, upvotecount, downvotecount;
TextInputLayout tilpReply;
ImageView prof_img;
Chip replyChip;
ToggleButton upvote, downvote;
ToggleButton replypop;
Button replyBtn;
CommentModel model;
RecyclerView replyRecycler;
public ViewHolder2(#NonNull View itemView){...}
public void bind(CommentModel commentModel){...}

Multiple class in Firebase, and when I get it by Recycler Adapter, the "adapter" declare in different if else statement. onStart and onStop not works

I am a newbie in Android Studio and I having some problem in Firebase Recycler Adapter. I got different database in Firebase and it follow to the user ID which is eBay(Example) and Kog. I want to work like if eBay having item, it will shows and else if Kog having item, it shows too. But in the code, I only declare adapter in if...else statement. This make onStart and onStop could not listening. Here is the code. Thanks all of you...
public RecyclerView recyclerView;
public RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference requests;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_history);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
database = FirebaseDatabase.getInstance();
requests = database.getReference("Users");
recyclerView = (RecyclerView)findViewById(R.id.order_history);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
loadOrders(common.currentUser.getUid());
}
private void loadOrders(String uid) {
DatabaseReference historyRef = FirebaseDatabase.getInstance().getReference("Users/orderHistory");
historyRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.hasChild("eBay")) {
FirebaseRecyclerAdapter<ebay_Order, orderViewHolder> adapter;
FirebaseRecyclerOptions<ebay_Order> options = new FirebaseRecyclerOptions.Builder<ebay_Order>()
.setQuery(requests.child(uid).child("eBay"), ebay_Order.class).build();
adapter = new FirebaseRecyclerAdapter<ebay_Order, orderViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull orderViewHolder holder, int position, #NonNull ebay_Order model) {
holder.txtOrderName.setText(model.getEbayId());
holder.txtOrderAmount.setText(model.getEbayAmount());
holder.txtOrderServices.setText(model.getOrderChoice());
}
#NonNull
#Override
public orderViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.order_history, parent, false);
return new orderViewHolder(view);
}
};
recyclerView.setAdapter(adapter);
}
if (snapshot.hasChild("KOG")){
FirebaseRecyclerAdapter<kog_Order, orderViewHolder> adapter;
FirebaseRecyclerOptions<kog_Order> options = new FirebaseRecyclerOptions.Builder<kog_Order>()
.setQuery(requests.child(uid).child("KOG"), kog_Order.class).build();
adapter = new FirebaseRecyclerAdapter<kog_Order, orderViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull orderViewHolder holder, int position, #NonNull kog_Order model) {
holder.txtOrderName.setText(model.getKogUsername());
holder.txtOrderAmount.setText(model.getKogAmounts());
holder.txtOrderServices.setText(model.getOrderChoice());
}
#NonNull
#Override
public orderViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.order_history, parent, false);
return new orderViewHolder(view);
}
};
recyclerView.setAdapter(adapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
#Override
public void onBackPressed(){
Intent intent = new Intent(this, InterPayMain.class);
orderHistory.this.finish();
startActivity(intent);
}
And the code for order View Holder
public class orderViewHolder extends RecyclerView.ViewHolder {
public TextView txtOrderName, txtOrderAmount, txtOrderServices;
public LinearLayout root;
public orderViewHolder(#NonNull View itemView) {
super(itemView);
root = itemView.findViewById(R.id.list_root);
txtOrderName = itemView.findViewById(R.id.order_id);
txtOrderAmount = itemView.findViewById(R.id.order_amount);
txtOrderServices = itemView.findViewById(R.id.order_choice);
}
And the error is
error: cannot find symbol adapter.startListening();
Is that got anyway to declare adapter in begining and able to work for different class.
As mentioned in the answer to this question: How to set two adapters to one RecyclerView?, a single RecyclerView can have only one adapter. You can create an adapter that has two different ViewHolders and chooses between them via overriding getItemViewType - see the question I linked for more information on implementing that solution.
An alternative is to have two separate RecyclerViews: one for each of your lists (eBay and Kog).

How to pass retrofit data in bundle to view pager fragments from activity?

In my activity i am receiving a game id from previous activity and using this id i am getting list of data from api. The method ("ApiCheats") in activity is used to get lis t of data.
I want to pass this list to my fragment in view pager, for this i used bundle but in fragment the bundle is null.
How should i pass bundle list to fragment , this data i am receiving through retrofit.
This is the Activity
public class GameListCheatsActivity extends AppCompatActivity {
private final String TAG = GameListCheatsActivity.class.getSimpleName();
public List<Cheats> Cheats;
ArrayList cheats = new ArrayList<Cheats>();
// public RecyclerView recyclerView;
String Gameid;
ViewPager viewPager;
ViewPagerAdapter adapter;
TabLayout tabLayout ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_list_cheats);
// recyclerView = (RecyclerView) findViewById(R.id.recycler_id);
// LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
// recyclerView.setLayoutManager(linearLayoutManager);
// recyclerView.setHasFixedSize(true);
Gameid = getIntent().getStringExtra("GameID");
tabLayout = (TabLayout) findViewById(R.id.tab_layout_id);
viewPager = (ViewPager) findViewById(R.id.viewpager_id);
adapter = new ViewPagerAdapter( getSupportFragmentManager());
ApiCheats();
adapter.AddFragment(new Fragment_Cheats(),"GameCheats");
adapter.AddFragment(new Fragment_Favourites(),"Favourites");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
if(state == 0){
View inflatedView = getLayoutInflater().inflate(R.layout.cheatitem, null);
}
if(state == 1){
View inflatedView = getLayoutInflater().inflate(R.layout.cheatitem, null);
}
}
});
}
public void ApiCheats()
{
ApiUtil.getServiceClass().getAllCheats(Gameid).enqueue(new Callback<List<Cheats>>() {
#Override
public void onResponse(Call<List<Cheats>> call, Response<List<Cheats>> response) {
if(response != null)
{
if(response.isSuccessful())
{
Cheats = response.body();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("cheatslist", (ArrayList<? extends Parcelable>) Cheats);
Fragment_Cheats fragment_cheats = new Fragment_Cheats();
fragment_cheats.setArguments(bundle);
}
}
Log.d(TAG, "Returned count " + Cheats.size());
GameListCheatsActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// CheatsAdapter adapter = new CheatsAdapter(getApplicationContext(), Cheats);
// recyclerView.setAdapter(adapter);
}
});
}
#Override
public void onFailure(Call<List<Cheats>> call, Throwable t) {
Log.d(TAG, "error loading from API");
}
});
}
}
this is one of the fragments class
public class Fragment_Cheats extends Fragment {
View v;
private RecyclerView mrecyclerview;
private List<Cheats> lstGameCheats;
public Fragment_Cheats()
{
}
// #Override
// public void onCreate(#Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// Bundle bundle = this.getArguments();
// if (bundle != null) {
// lstGameCheats = bundle.getParcelable("cheatslist");
// }
//
// }
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_fragment__cheats, container, false);
mrecyclerview = (RecyclerView)v.findViewById(R.id.recyclerview_cheats);
Bundle bundle = this.getArguments();
if (bundle != null) {
lstGameCheats = bundle.getParcelable("cheatslist");
}
CheatsAdapter recyclerAdapter = new CheatsAdapter(getContext(),lstGameCheats);
mrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
mrecyclerview.setAdapter(recyclerAdapter);
return v;
}
}
this is view pager adapter
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> lstFragment = new ArrayList<>();
private final List<String> lstTitles = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return lstFragment.get(position);
//return null;
}
#Override
public int getCount() {
return lstTitles.size();
//return 0;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return lstTitles.get(position);
}
public void AddFragment(Fragment fragment,String title){
lstFragment.add(fragment);
lstTitles.add(title);
}
}
You should set the Cheats to the Fragment which have added to your ViewPagerAdater, but according to your code you just set the data to a new fragment instance.
According to the Fragment_Cheats code, if you want to invoke getArgument() in onCreate() method, you should invoke fragment.setArgument() before the fragment add to the ViewPagerAdapter.
But in your situation it is not possible, because the data get from the network.
So, two step
Set data to the correct Fragment_Cheats instance
Notify Fragment_Cheats data changed, refresh the View state in the fragment
Replace your onResponse()
#Override
public void onResponse(Call<List<Cheats>> call, Response<List<Cheats>> response) {
if(response != null)
{
if(response.isSuccessful())
{
Cheats = response.body();
Fragment_Cheats fragment_cheats = adapter.getCheatFragment()
fragment_cheats.setDatas(Cheats);
}
}
Log.d(TAG, "Returned count " + Cheats.size());
GameListCheatsActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// CheatsAdapter adapter = new CheatsAdapter(getApplicationContext(), Cheats);
// recyclerView.setAdapter(adapter);
}
});
}
Fragment_Cheats add setDatas() method
public void setDatas(List<Cheats> datas) {
this.lstGameCheats = datas;
// and set the datas to the RecylerView adapter
recyclerviewAdapter.notifyDataSetChanged();
}

Using FirebaseUI for firebase recyclerView in android

i am a new comer in android development and facing some problems using firebase ui.
i wanted to retrieve data from my firebase database and show it on my recyclerView.
but i am constantly getting an error while making FirebaseRecyclerAdapter.
Here is My Code Sample:
public class UsersActivity extends AppCompatActivity {
private Toolbar userToolbar;
private RecyclerView usersList;
private DatabaseReference mUsersDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_users);
userToolbar = (Toolbar) findViewById(R.id.users_toolbar);
setSupportActionBar(userToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Users");
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
usersList = (RecyclerView) findViewById(R.id.users_list);
usersList.setHasFixedSize(true);
usersList.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(
Users.class,
R.layout.single_user_list_layout,
UsersViewHolder.class,
mUsersDatabase
) {
#Override
protected void onBindViewHolder(#NonNull UsersViewHolder holder, int position, #NonNull Users model) {
holder.setName(model.getName());
}
#NonNull
#Override
public UsersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return null;
}
};
usersList.setAdapter(firebaseRecyclerAdapter);
}
public static class UsersViewHolder extends RecyclerView.ViewHolder
{
View mView;
public UsersViewHolder(#NonNull View itemView) {
super(itemView);
mView = itemView;
}
public void setName(String name)
{
TextView userNameView = (TextView) mView.findViewById(R.id.single_user_name);
userNameView.setText(name);
}
}
}
The Error i'm getting is this:
please help!!
Sorry wanted to comment but i ain't got enough points to do so.
Try this first, if it doesnt work try using FirebaseRecyclerOptions
(The latest version (3.x) of FirebaseUI implements a different method ofinitializing a FirebaseRecyclerAdapter than previous versions.)
Make your " firebaseRecyclerAdapter " variable global, so you would have something like this.
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(
Users.class,
R.layout.single_user_list_layout,
UsersViewHolder.class,
mUsersDatabase
)

FragmentStatePager instantiate my Fragment twice

I am using the following the custom viewPager with FragmentStatePagerAdapter to create a set of fragments for user to write the specific profile. The data of the user can be retrieved by SQL with respect to the position of the child page of the viewpager. When it comes to the execution , I see that the fragment is created twice whenever the first time to be load and swipe to the other uncached pages . I have found the referenceFragment Hash map to retrieve the current fragment to be load once only instead of two fragments to be loaded. COuld you please tell me the better way to load the fragment once only ?
The below is my working :
static SectionsPagerAdapter mSectionsPagerAdapter;
static CustomViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSectionsPagerAdapter = new SectionsPagerAdapter(fm);
dotsCount = mSectionsPagerAdapter.getCount();
dots = new ImageView[dotsCount];
dots[0] = dot1;
dots[1] = dot2;
dots[2] = dot3;
dots[3] = dot4;
dots[4] = dot5;
dots[5] = dot6;
dots[6] = dot7;
setUiPageViewController();
isTablet= ReadExcel.isTabletDevice(this);
mViewPager = (CustomViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setEnabled(true);
mViewPager.setOffscreenPageLimit(0);
mViewPager.setOnPageChangeListener(viewPagerPageChangeListener);
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
// PlaceholderFragment fragment = new PlaceholderFragment();
PlaceholderFragment fragment = ((SectionsPagerAdapter)mViewPager.getAdapter()).getFragment(sectionNumber);
if(fragment==null){
fragment = new PlaceholderFragment();
}
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setTag(String.valueOf(sectionNumber));
fragment.setArguments(args);
return fragment;
}
public String getFTag(){
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
....}}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
private Map<Integer, PlaceholderFragment> mPageReferenceMap = new HashMap<Integer, PlaceholderFragment>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getItemPosition(Object object) {
return PagerAdapter.POSITION_NONE;
}
#Override
public Fragment getItem(int position) {
for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
PlaceholderFragment pf = PlaceholderFragment.newInstance(position);
mPageReferenceMap.put(Integer.valueOf(position), pf);
return pf;
}
#SuppressWarnings("deprecation")
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
mPageReferenceMap.remove(Integer.valueOf(position));
// mPageReferenceMap.remove(position);
}
public PlaceholderFragment getFragment(int key) {
return mPageReferenceMap.get(key);
}
#Override
public int getCount() {
return 7;
}
#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);
}
return null;
}
}

Resources