Passing data to CustomView via method - android-custom-view

I've created a custom view that extends LinearLayoutCompat. The view works fine if I hard code the data variables within the constructor, however, I'm wanting to pass data to this view from various different fragments, however I get null object errors when I do this.
fragment_profile:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
...
<com.topper.topper.ui.profile.ProfileSummaryCardView
android:id="#+id/friendsummaryclasstest"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="0dp"
android:orientation="vertical" />
...
<data>
<variable
name="ProfileViewModel"
type="com.topper.topper.ui.profile.ProfileViewModel" />
</data>
</layout>
ProfileFragment:
public class ProfileFragment extends Fragment {
private ProfileViewModel mViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
FragmentProfileBinding binding = DataBindingUtil.inflate(inflater, R.layout.fragment_profile, container, false);
mViewModel = ViewModelProviders.of(this).get(ProfileViewModel.class);
binding.setProfileViewModel(mViewModel);
binding.getProfileViewModel();
return binding.getRoot();
}
#Override
public void onViewCreated(#NotNull View view, #Nullable Bundle savedInstanceState) {
ProfileSummaryCardView friendSummaryCard = view.findViewById(R.id.friendsummaryclasstest);
friendSummaryCard.setParameters(getString(R.string.title_friends), mViewModel.getFriendNames(), mViewModel.getFriendPics());
}
}
ProfileSummaryCardView (CustomView):
public class ProfileSummaryCardView extends LinearLayoutCompat {
private String cardTitle;
private ArrayList<String> imgURLs;
private String[] names;
private Context mContext;
public ProfileSummaryCardView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
final ViewProfileSummaryCardBinding binding = ViewProfileSummaryCardBinding.inflate(LayoutInflater.from(mContext), this, true);
if (imgURLs.size() == 0) {
binding.profileCard.setVisibility(View.GONE);
} else if (imgURLs.size() <= 4) {
binding.profileCardGridrowb.setVisibility(View.GONE);
}
binding.profileCardTitle.setText(cardTitle);
ImageView[] imageViewList = {binding.profileCardIImg,
binding.profileCardIiImg,
binding.profileCardIiiImg,
binding.profileCardIvImg,
binding.profileCardVImg,
binding.profileCardViImg,
binding.profileCardViiImg,
binding.profileCardViiImg};
TextView[] textViewList = {binding.profileCardIName,
binding.profileCardIiName,
binding.profileCardIiiName,
binding.profileCardIvName,
binding.profileCardVName,
binding.profileCardViName,
binding.profileCardViiName,
binding.profileCardViiName};
for (int i = 0; i < imgURLs.size(); i++) {
gridImageSetup(imageViewList[i], imgURLs.get(i));
textViewList[i].setText(names[i]);
}
}
public void setParameters(String pTitle, String[] pNameArray, ArrayList pPicURLArray) {
this.cardTitle = pTitle;
this.imgURLs = pPicURLArray;
this.names = pNameArray;
invalidate();
}
private void gridImageSetup(ImageView target, String url) {
Glide.with(this)
.load(url)
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.transform(new FitCenter(), new RoundedCorners(25))
.into(target);
}
}
It seems like the customview is initialized before the setParameters method call I make in my fragment as the data objects are null when I try and run the above.
Any help would be greatly appreciated.

So, I figured out the fix for this issue and it's was a face-palm moment as it was a really simple fix.
I cut and pasted everything in the constructor of the custom view (except the inflate) into the setParameters method, as below:
public class ProfileSummaryCardView extends LinearLayoutCompat {
private String cardTitle;
private ArrayList<String> imgURLs;
private String[] names;
private Context mContext;
public ProfileSummaryCardView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
final ViewProfileSummaryCardBinding binding = ViewProfileSummaryCardBinding.inflate(LayoutInflater.from(mContext), this, true);
}
public void setParameters(String pTitle, String[] pNameArray, ArrayList pPicURLArray) {
this.cardTitle = pTitle;
this.imgURLs = pPicURLArray;
this.names = pNameArray;
if (imgURLs.size() == 0) {
binding.profileCard.setVisibility(View.GONE);
} else if (imgURLs.size() <= 4) {
binding.profileCardGridrowb.setVisibility(View.GONE);
}
binding.profileCardTitle.setText(cardTitle);
ImageView[] imageViewList = {binding.profileCardIImg,
binding.profileCardIiImg,
binding.profileCardIiiImg,
binding.profileCardIvImg,
binding.profileCardVImg,
binding.profileCardViImg,
binding.profileCardViiImg,
binding.profileCardViiImg};
TextView[] textViewList = {binding.profileCardIName,
binding.profileCardIiName,
binding.profileCardIiiName,
binding.profileCardIvName,
binding.profileCardVName,
binding.profileCardViName,
binding.profileCardViiName,
binding.profileCardViiName};
for (int i = 0; i < imgURLs.size(); i++) {
gridImageSetup(imageViewList[i], imgURLs.get(i));
textViewList[i].setText(names[i]);
}
invalidate();
}
private void gridImageSetup(ImageView target, String url) {
Glide.with(this)
.load(url)
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.transform(new FitCenter(), new RoundedCorners(25))
.into(target);
}
}

Related

Error null exception in "for" construct xamarin android. Where is incorrect?

This method returns the number of types of Views that will be created by getView method.
public class CustomAdapter : BaseAdapter{
private const int TYPE_ITEM = 0;
private const int TYPE_SEPARATOR = 1;
private List<string> mData;
private TreeSet sectionHeader;
private LayoutInflater mInflater;
public CustomAdapter(Context context, List<string> Data) {
mInflater = (LayoutInflater) context
.GetSystemService(Context.LayoutInflaterService);
this.mData=Data;
}
public void addItem(string item) {
mData.Add(item);
NotifyDataSetChanged();
}
public void addSectionHeaderItem(string item) {
mData.Add(item);
//sectionHeader.Add(mData.Count - 1);
NotifyDataSetChanged();
}
public int getItemViewType(int position) {
return sectionHeader.Contains(position) ? TYPE_SEPARATOR : TYPE_ITEM;
}
public int getViewTypeCount {
get{ return 2; }
}
public override int Count {
get {return mData.Count;}
}
public override Java.Lang.Object GetItem(int position) {
return mData[position];
}
public override long GetItemId(int position) {
return position;
}
public override View GetView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int rowType = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
switch (rowType) {
case TYPE_ITEM:
convertView = mInflater.Inflate(Resource.Layout.textViewItemsSeparator, parent);
holder.textView = (TextView) convertView.FindViewById(Resource.Id.textviewHeaderItems);
break;
case TYPE_SEPARATOR:
convertView = mInflater.Inflate(Resource.Layout.textViewHeaderItems, parent);
holder.textView = (TextView) convertView.FindViewById(Resource.Id.textviewItemsSeparator);
break;
}
convertView.Tag=holder;
} else {
holder = (ViewHolder)convertView.Tag as ViewHolder;
}
holder.textView.Text=mData[position];
return convertView;
}
public class ViewHolder:Java.Lang.Object {
public TextView textView;
}
}
ListView lst;
string[] items = new string[] { "Alternative Rock","Classical",...........};
List<string> listItems;
private CustomAdapter mAdapter;
public override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
// Create your fragment here
}
public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Use this to return your custom view for this Fragment
// return inflater.Inflate(Resource.Layout.YourFragment, container, false);
listItems = new List<string> (items);
return inflater.Inflate (Resource.Layout.GenerFragment, container, false);
}
public override void OnActivityCreated(Bundle savedInstanceState)
{
base.OnActivityCreated(savedInstanceState);
lst = View.FindViewById<ListView> (Resource.Id.lstGenres);
//lst.Adapter = new ArrayAdapter<string>(Activity, Resource.Layout.textViewHeaderItems,Resource.Id.textviewHeaderItems, items);
//lst = View.FindViewById<ListView> (Resource.Id.lst_genre);
//lst.SetAdapter(new ArrayAdapter<String>(this.Activity, Resource.Layout.GenerFragment, items));
//mAdapter=new CustomAdapter();
for (int i = 0; i < listItems.Count(); i++) {
mAdapter.addItem (listItems[i]);
if (i == 0) {
mAdapter.addSectionHeaderItem ("Music");
} else if(i==13) {
mAdapter.addSectionHeaderItem ("Audio");
}
}
lst.Adapter = new CustomAdapter (Activity, listItems);
I spent much time for looking for errors but I have no idea why It was null. although It got a data from list
mAdapter.addItem (listItems[i]); -> null exception when I debug on device. Where is incorrect?
in OnActivityCreated you are referencing listItems
for (int i = 0; i < listItems.Count(); i++) {
however, listItems is null. You initialize it in OnCreateView, which has not been executed yet. You need to be sure that listItems is initialized before you attempt to reference it.
Additionally, you are attempting to add items to mAdapter, but it's never been initialized (as far as I can see)
you declare it here, but it will be NULL until you initalize it
private CustomAdapter mAdapter;
here is the initialization, which is commented out
//mAdapter=new CustomAdapter();
when you attempt to reference it here, it is still null, and will throw a Null Reference Exception
mAdapter.addItem (listItems[i]);

Adapter showing the wrong images while using Fresco library

i have used fresco library to load images in the adapter. but the images are not set correctly as i expected. Here is my code. please help me. thanks in advance.
public class HomeListingAdapter_recyler1 extends RecyclerView.Adapter {
private Context context;
private ArrayList propertyItemList;
private ImageLoader mImageLoader;
public HomeListingAdapter_recyler1(HomeListingActivity_recycler propertyViews, ArrayList propertyItemList) {
Fresco.initialize(propertyViews);
this.propertyItemList = propertyItemList;
this.context = propertyViews;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.property_item_layout,parent,false);
CustomViewHolder viewHolder = new CustomViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(final CustomViewHolder holder, final int position) {
mImageLoader = VolleySingletonPattern.getInstance(context).getImageLoader();
holder.txtPropertyName.setText(propertyItemList.get(position).ville);
holder.txtPropertyType.setText(propertyItemList.get(position).bienName);
if(propertyItemList.get(position).pieces.equalsIgnoreCase("0")){
holder.txtPropertySurfaceArea.setText(propertyItemList.get(position).surface+" "+context.getString(R.string.meter_square));
}else{ holder.txtPropertySurfaceArea.setText(propertyItemList.get(position).surface+" "+context.getString(R.string.meter_square)+" - "+ propertyItemList.get(position).pieces+" "+context.getResources().getString(R.string.pieces));
}
holder.txtPropertyPrice.setText(propertyItemList.get(position).montantLoyer);
Uri imageUri;
try {
if(!TextUtils.isNullOrEmpty(propertyItemList.get(position).photo)) {
imageUri = Uri.parse(propertyItemList.get(position).photo);
holder.imgPropertyImage.setVisibility(View.VISIBLE);
holder.imgPropertyImage.setImageURI(imageUri);
}
} catch (Exception e) {
}
}
#Override
public int getItemCount() {
return propertyItemList.size();
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
SimpleDraweeView imgPropertyImage;
public TextView txtPropertyName , txtPropertyType , txtPropertySurfaceArea ,txtPropertyPrice;
public CustomViewHolder(View itemView) {
super(itemView);
imgPropertyImage = (SimpleDraweeView) itemView.findViewById(R.id.image_property);
txtPropertyName = (TextView) itemView.findViewById(R.id.txt_property_name);
txtPropertyType = (TextView) itemView.findViewById(R.id.txt_property_type);
txtPropertySurfaceArea = (TextView) itemView.findViewById(R.id.txt_property_surface_piece);
txtPropertyPrice = (TextView) itemView.findViewById(R.id.txt_property_price);
}
}
}
Your imgPropertyImage should be a SimpleDraweeView, not an ImageView.

How can I show Video List properly?

I've been searching everywhere for the solution, but it has come to a dead end.
Please help!
I record and save the video as the follow:
File DirectoryFile = new File(VideoPath);
recorder.setOutputFile(DirectoryFile.getAbsolutePath());
I load all the videos and set the ListView adapter from the userPath as follow:
private File[] getNewImageFilesWithFilters() {
File directory = new File(UserSavedDirectoryPATH);
return directory.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase(Locale.getDefault()).endsWith(".mp4")
|| name.toLowerCase(Locale.getDefault()).endsWith(".mkv");
}
});
}
public void LoadListView() {
for (File file : listFile){
mVideoListViewObject = new VideoListViewObject();
mVideoListViewObject.setName(file.getName());
mVideoListViewObject.setVideoUrl(file.getAbsolutePath());
VideoListViewObject_List.add(mVideoListViewObject);
}
mVideoListViewAdapter = new VideoListAdapter(this, VideoListViewObject_List);
mListView.setAdapter(mVideoListViewAdapter);
}
The ListView Adapter:
public class VideoListAdapter extends BaseAdapter {
private List<VideoListViewObject> VideoObjectList;
private Context mContext;
public VideoListAdapter(Context context, List<VideoListViewObject> newList){
this.mContext = context;
this.VideoObjectList = newList;
}
#Override
public int getCount() {
return VideoObjectList.size();
}
#Override
public VideoListViewObject getItem(int position) {
return VideoObjectList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.listview_layout, parent, false);
viewHolder.imageView = (ImageView)convertView.findViewById(R.id.ListViewImage);
viewHolder.layout = (RelativeLayout)convertView.findViewById(R.id.ListViewLayout);
convertView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder)convertView.getTag();
}
Bitmap bmThumbnail = ThumbnailUtils.createVideoThumbnail(VideoObjectList.get(position).getVideoUrl(),Thumbnails.MICRO_KIND);
viewHolder.imageView.setImageBitmap(bmThumbnail);
The problem is the list is slow to load, especially when there are a lot of videos.
This causes my VideoaAtivity to start very slow.
I love Piscasso and Universal Image Loader, but they only support images.
Does anyone know a better solution or a library that would help with the performance?
Thank you very much.
I just modified my own application to do similar logic to pre-create the thumbnails which made the list scroll very fast at the start, Add the thumbnail bitmap to the videoListViewObject and create the thumbnail
when loading the video list. this way you do not have to create it every time getView is called in your adapter.
public class VideoListViewObject{
private Bitmap bitmap = null;
............................
public void setBitmap(Bitmap bitmap)
{
this.bitmap = bitmap;
}
public Bitmap getBitmap()
{
return this.bitmap;
}
}
public void LoadListView() {
for (File file : listFile){
mVideoListViewObject = new VideoListViewObject();
mVideoListViewObject.setName(file.getName());
mVideoListViewObject.setVideoUrl(file.getAbsolutePath());
Bitmap bmThumbnail = ThumbnailUtils.createVideoThumbnail(VideoObjectList.get(position).getVideoUrl(),Thumbnails.MICRO_KIND);
mVideoListViewObject.setBitmap(bmThumbnail);
VideoListViewObject_List.add(mVideoListViewObject);
}
mVideoListViewAdapter = new VideoListAdapter(this, VideoListViewObject_List);
mListView.setAdapter(mVideoListViewAdapter);
}
then change your BaseAdapter code to only create the thumbnail if it is null,
public class VideoListAdapter extends BaseAdapter {
private List<VideoListViewObject> VideoObjectList;
private Context mContext;
public VideoListAdapter(Context context, List<VideoListViewObject> newList){
this.mContext = context;
this.VideoObjectList = newList;
}
#Override
public int getCount() {
return VideoObjectList.size();
}
#Override
public VideoListViewObject getItem(int position) {
return VideoObjectList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.listview_layout, parent, false);
viewHolder.imageView = (ImageView)convertView.findViewById(R.id.ListViewImage);
viewHolder.layout = (RelativeLayout)convertView.findViewById(R.id.ListViewLayout);
convertView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder)convertView.getTag();
}
VideoListViewObject mVideoListViewObject = getItem(position);
Bitmap bmThumbnail = mVideoListViewObject.getBitmap();
if(bmThumbnail==null)
{
bmThumbnail = ThumbnailUtils.createVideoThumbnail(VideoObjectList.get(position).getVideoUrl(),Thumbnails.MICRO_KIND);
}
viewHolder.imageView.setImageBitmap(bmThumbnail);

Getting wrong position in custom ListView while scrolling

I am getting wrong position in custom ListView while scrolling.
I have tried the ViewHolder pattern and an ArrayAdapter but both giving the same problem.
If I reproduce the code using Java then I am getting the proper position while scrolling.
So is it Xamarin architecture bug ?
Below is my sample code:
Activity Class
namespace ArrayAdapterDemoApp
{
[Activity(Label = "ArrayAdapterDemoApp", MainLauncher = true,
Icon ="#drawable/icon")]
public class MainActivity : Activity
{
private static List<DataBean> _ItemsList = new List<DataBean>();
private static CustomAdapter _adapter;
private ListView _listview;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
_listview = FindViewById<ListView>(Resource.Id.mylist);
DataBean obj1 = new DataBean();
obj1.Name = "AA";
obj1.City = "11";
_ItemsList.Add(obj1);
DataBean obj2 = new DataBean();
obj2.Name = "BB";
obj2.City = "22";
_ItemsList.Add(obj2);
DataBean obj3 = new DataBean();
obj3.Name = "CC";
obj3.City = "33";
_ItemsList.Add(obj3);
...
DataBean obj15 = new DataBean();
obj15.Name = "OO";
obj15.City = "1010";
_ItemsList.Add(obj15);
_adapter = new CustomAdapter(this, _ItemsList);
_listview.Adapter = _adapter;
}
}
}
Custom Adapter
namespace ArrayAdapterDemoApp
{
public class CustomAdapter : ArrayAdapter<DataBean>
{
private class TaskViewHolder : Java.Lang.Object
{
public TextView tvName;
public TextView tvCity;
}
List<DataBean> listData;
Activity _context;
int _position;
public CustomAdapter(Activity context, List<DataBean> dataList)
: base(context, Resource.Layout.adapter_row, dataList)
{
this._context = context;
this.listData = dataList;
}
public override long GetItemId(int position)
{
return position;
}
public override int Count
{
get { return listData.Count; }
}
//With View Holder
public override View GetView(int position, View convertView, ViewGroup parent)
{
DataBean data = listData[position];
TaskViewHolder viewHolder= null; // view lookup cache stored in tag
if (convertView == null)
{
viewHolder = new TaskViewHolder();
LayoutInflater inflater = LayoutInflater.From(_context);
convertView = inflater.Inflate(Resource.Layout.adapter_row, parent, false);
viewHolder.tvName = convertView.FindViewById<TextView>(Resource.Id.text1);
viewHolder.tvCity = convertView.FindViewById<TextView>(Resource.Id.text2);
convertView.Tag = viewHolder;
}
if(viewHolder==null)
{
viewHolder = (TaskViewHolder)convertView.Tag;
}
viewHolder.tvName.Text = data.Name;
viewHolder.tvCity.Text = data.City;
return convertView;
}
}
}
DataBean Class
namespace ArrayAdapterDemoApp
{
public class DataBean
{
public string Name { get; set; }
public string City { get; set; }
}
}
I had also same issue so I resolved it by just Tag the position to the view.for example.
//iv_delete is a imageview
holder.iv_delete.Tag = position;
and get the position from the Tag
For me it was like that
int finalPosition = (Integer)holder.iv_delete.Tag.IntValue();
Enjoy!!!!!
Add in your adapter class this method:
public DataBean GetItemAtPosition(int position)
{
return this.listData[position];
}
You can tag the position of each row to the control to get the correct position or
Another method is by using action event binding to each view row. This also solves duplicate method call issue.
this might be helpful: http://appliedcodelog.blogspot.in/2015/07/working-on-issues-with-listview-in.html#WrongPosition

Memory leak with view pager and fragment

In this part of my application there is a ViewPager contents in a fragment,
when i replace the fragment contains the viewpager android doesn't clear the memory.
How can I clear the memory?
this is the adapter for the listview:
public class LineeAdapter extends ArrayAdapter<Linea> {
private final List<Linea> list;
private final Activity context;
private final int layout;
public LineeAdapter(Activity context,int layout, List<Linea> list) {
super(context, layout, list);
this.context = context;
this.list = list;
this.layout=layout;
}
static class ViewHolder {
protected TextView text;
protected TextView text1;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(layout, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.cod_linea);
viewHolder.text1 = (TextView) view.findViewById(R.id.descrizione_linea);
view.setTag(viewHolder);
} else {
view = convertView;
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(list.get(position).getCod_Linea());
holder.text1.setText(list.get(position).getDesc_Linea());
return view;
}
this is the fragmet contain in the view pager
public class TempiAtt_Linee extends Fragment
{
View view;
ListView lw;
int dati;
LineeAdapter adapter;
List<Linea> linee ;
static TempiAtt_Linee newInstance(int num)
{
TempiAtt_Linee f = new TempiAtt_Linee();
return f;
}
#Override
public void onDestroyView()
{
super.onDestroyView();
getView().destroyDrawingCache();
linee.clear();
adapter.notifyDataSetChanged();
adapter.clear();
view = null;
lw = null;
linee = null;
System.gc();
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
linee= new ArrayList<Linea>();
for (int i = 0; i < Main.GeneralObject.getLinee().size(); i++)
{
this.linee.add(Main.GeneralObject.getLinee().get(i));
}
lw = (ListView) getView().findViewById(R.id.list_view);
adapter = new LineeAdapter(getActivity(), R.layout.row_linea, linee);
lw.setAdapter(adapter);
lw.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3)
{
ArrayList<Percorso> tratte = linee.get(position).getPercorsi();
Fragment fragment = new TempiAtt_Percorsi();
FragmentManager fragmentManager = getActivity()
.getSupportFragmentManager();
Bundle temp = new Bundle();
temp.putString("linea", linee.get(position).getCod_Linea()
.replace(" ", "_"));
temp.putSerializable("tratte",
SerializerClass.serializeObject(tratte));
fragment.setArguments(temp);
fragmentManager.beginTransaction().addToBackStack(null)
.replace(R.id.content_frame, fragment).commit();
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.generic_listview, container, false);
return view;
}
}
and this is the fragment of the viewpager:
public class TempiAtt extends Fragment {
// list contains fragments to instantiate in the viewpager
List<Fragment> fragments = null;
int NUM = 3;
List<String> fragmentTitles = null;
// page adapter between fragment list and view pager
private MyAdapter mPagerAdapter = null;
// view pager
private ViewPager mViewPager;
private Handler handler;
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.main_prova, container, false);
return view;
}
public void clear() {
if (null != mViewPager) {
mViewPager.removeAllViews();
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewPager = (ViewPager) getView().findViewById(R.id.pager);
fragments = new Vector<Fragment>();
setRetainInstance(true);
fragmentTitles = new Vector<String>();
Bundle scheda = new Bundle();
scheda.putInt("scheda", 0);
// creating fragments and adding to list
fragments.add(Fragment.instantiate(getActivity(),
TempiAtt_Linee.class.getName(), scheda));
fragmentTitles.add(getActivity().getResources().getString(
R.string.urbana_como));
Bundle scheda1 = new Bundle();
scheda1.putInt("scheda", 1);
fragments.add(Fragment.instantiate(getActivity(),
TempiAtt_Linee.class.getName(), scheda1));
fragmentTitles.add(getActivity().getResources().getString(
R.string.extraurbana));
Bundle scheda2 = new Bundle();
scheda2.putInt("scheda", 2);
fragments.add(Fragment.instantiate(getActivity(),
TempiAtt_Linee.class.getName(), scheda2));
fragmentTitles.add(getActivity().getResources().getString(
R.string.urbana_cantu));
View pagerStrip = super.getView().findViewById(R.id.pagerTabStrip);
if (pagerStrip instanceof PagerTabStrip) {
PagerTabStrip pagerTabStrip = (PagerTabStrip) pagerStrip;
pagerTabStrip.setDrawFullUnderline(true);
pagerTabStrip.setTabIndicatorColorResource(R.color.bianco);
} else if (pagerStrip instanceof PagerTitleStrip) {
PagerTitleStrip pagerTitleStrip = (PagerTitleStrip) pagerStrip;
pagerTitleStrip.setTextColor(getResources().getColor(
android.R.color.white));
}
/*
* this.mPagerAdapter = new PagerAdapter(getChildFragmentManager(),
* fragments, fragmentTitles);
* mViewPager.setAdapter(this.mPagerAdapter);
* mViewPager.setCurrentItem(0);
*/
mPagerAdapter = new MyAdapter(getChildFragmentManager());
handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
mViewPager.setAdapter(mPagerAdapter);
}
});
mViewPager.setOffscreenPageLimit(2);
}
#Override
public void onDestroyView() {
super.onDestroyView();
onDestroy();
deleteCard();
clear();
view = null;
System.gc();
}
public void deleteCard() {
// Reduce the card counter by one
NUM -= 3;
for (int i = 0; i < fragments.size(); i++) {
fragments.remove(i);
Log.e("SONO IO", fragments.size() + "");
}
mPagerAdapter.notifyDataSetChanged();
}
private class MyAdapter extends FragmentPagerAdapter {
private SparseArray<WeakReference<TempiAtt_Linee>> mPageReferenceMap = new SparseArray<WeakReference<TempiAtt_Linee>>();;
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
return getFragment(index);
}
#Override
public int getCount() {
return NUM;
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
public TempiAtt_Linee getFragment(int key) {
WeakReference<TempiAtt_Linee> weakReference = mPageReferenceMap
.get(key);
if (null != weakReference) {
return (TempiAtt_Linee) weakReference.get();
} else {
return null;
}
}
public Object instantiateItem(ViewGroup container, int position) {
TempiAtt_Linee tempiAttLinee = TempiAtt_Linee.newInstance(position);
mPageReferenceMap.put(Integer.valueOf(position),
new WeakReference<TempiAtt_Linee>(tempiAttLinee));
return super.instantiateItem(container, position);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
mPageReferenceMap.remove(Integer.valueOf(position));
}
}
}

Resources