Unable to set automatically image slide in android Fragment - android

In my app I want an image slider.I already do that with view pager but I want image change automatically in every 2seconds. I am unable to do that.
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_about, container,false);
viewPager = (ViewPager) rootView.findViewById(R.id.viewPager);
adapter = new CustomSwipeAdapter(this.getActivity());
viewPager.setAdapter(adapter);
indicator = (CircleIndicator) rootView.findViewById(R.id.indicator);
indicator.setViewPager(viewPager);
return rootView;
}
this is my fragment class.
public class CustomSwipeAdapter extends PagerAdapter {
private int[] image_resource = {R.drawable.sample_1, R.drawable.sample_2};
private Context ctx;
private LayoutInflater layoutInflater;
public CustomSwipeAdapter(Context ctx) {
this.ctx = ctx;
}
#Override
public int getCount() {
return image_resource.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return (view == object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View item_view = layoutInflater.inflate(R.layout.image_swipe_layout, container, false);
ImageView imageview = (ImageView) item_view.findViewById(R.id.image_view);
imageview.setImageResource(image_resource[position]);
container.addView(item_view);
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout)object);
}
}
this is my adapter class.I want that image change automatically.Please help me.Thanks.

A code I had written a really long time ago which does something similar, maybe this can help you.
final Handler handler = new Handler();
final Runnable update = () -> {
if (currentPage == list.size()) {
currentPage = 0;
}
pager.setCurrentItem(currentPage++, true);
};
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(update);
}
}, 2500, 2500);
#Override
protected void onDestroy() {
super.onDestroy();
timer.cancel();
}
So you set a timer which gets called after a certain interval of time (~2.5 seconds here) and when it does, you check if the current page of the adapter has reached the end then reset it back to 0 else increment it.

Related

ViewPager and ImageGallery

The problem is this:
When you first choose a picture - everything is fine. If you swipe, and press the "back" button, after you open another image then will open last image which will opened.
The correct position is passed through the Bundle. I don’t understand where to look for the error.
public class ViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public ViewPagerAdapter() {
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.image_fullscreen, container, false);
ImageView imageView = view.findViewById(R.id.image_fScreen);
Hit hit = hits.get(position);
Picasso.get().load(hit.getLargeImageURL())
.into(imageView);
container.addView(view);
return view;
}
#Override
public int getCount() {
return hits.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
}
}
DialogFragment:
public class FullScreenDialogFragment extends DialogFragment {
private ArrayList<Hit> hits;
private ViewPager viewPager;
private ViewPagerAdapter viewPagerAdapter;
private TextView author;
private TextView count;
private int selectedPosition;
private Button buttonShare;
private static FullScreenDialogFragment fullScreenDialogFragment;
private int rlyPosition;
public static FullScreenDialogFragment getInstance() {
if (fullScreenDialogFragment == null) {
fullScreenDialogFragment = new FullScreenDialogFragment();
}
return fullScreenDialogFragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_FRAME, R.style.DialogStyle);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.image_viewpager, container, false);
viewPager = view.findViewById(R.id.viewpager);
author = view.findViewById(R.id.author);
buttonShare = view.findViewById(R.id.btnShare);
count = view.findViewById(R.id.count);
hits = (ArrayList<Hit>) getArguments().getSerializable("hits");
selectedPosition = getArguments().getInt("position");
viewPagerAdapter = new ViewPagerAdapter();
viewPager.setAdapter(viewPagerAdapter);
viewPager.addOnPageChangeListener(onViewPageChangeListener);
setItem(selectedPosition);
return view;
}
private void setItem(int pos) {
viewPager.setCurrentItem(pos, true);
setItemInfo(selectedPosition);
}
private void setItemInfo(int pos) {
count.setText((pos + 1) + " of " + hits.size());
Hit hit = hits.get(pos);
author.setText(hit.getUser());
}
ViewPager.OnPageChangeListener onViewPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
setItemInfo(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
I Guess the Problem is here
private void setItem(int pos) {
viewPager.setCurrentItem(pos, true);
setItemInfo(selectedPosition);
}
You might be passing the selectedPosition instead of currentPosition
Please check.
My problem was in creating DialogFramgent object.
I did it him in Singlton pattern and called it with old data.
Now in OnClick i'm created new object DialogFramget and him get new values.
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fullScreenDialog = new FullScreenDialogFragment();
fullScreenDialog.setArguments(bundle);
fullScreenDialog.show(fragmentTransaction, "");

Auto slideshow loop with ViewPager

How would I turn my swipe-able ViewPager into a auto looping slideshow? I'v read other post referencing to use a Handler or Timer but I'm not sure which one would be best. Iv posted my code below.
Update:
After following some old posts and comments Iv been trying to initiate a timer to loop through the ViewPager slides. The issue is now the Timer is not working, also not getting any errors either. Any thoughts? Iv added the Timer code to the MainActivity code below.
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ViewPager viewPager;
customSwipeAdapter swipeAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = findViewById(R.id.viewPager);
swipeAdapter = new customSwipeAdapter(this);
viewPager.setAdapter(swipeAdapter);
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
int currentPage = 0;
int NUM_PAGES = 3;
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
viewPager.setCurrentItem(currentPage++, true);
}
});
}
}, 500, 3000);
}
}
CustomSwipeAdapter.java
public class customSwipeAdapter extends PagerAdapter {
private int [] image_resources = {R.drawable.SlideOne,R.drawable.SlideTwo,R.drawable.SlideThr,R.drawable.SlideFour};
private Context context;
private LayoutInflater layoutInflater;
public customSwipeAdapter(Context context){
this.context = context;
}
#Override
public int getCount() {
return image_resources.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == (LinearLayout)object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View item_view = layoutInflater.inflate(R.layout.swipe_layout,container,false);
ImageView imageView = (ImageView) item_view.findViewById(R.id.imageView);
imageView.setImageResource(image_resources[position]);
container.addView(item_view);
return item_view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((LinearLayout)object);
}
}

How can I implement a rotative banner for my Android app?

On my login activity I would like to have a banner (3 actually) which would switch by certain time. Just like news on a website. With an arrow to pass to the next one, but mainly that passes automatically.
An example of what I want, these images on Tinder login screen switch when I swipe or just wait:
How do I do something like this on Android? Is there a way to do it natively? or at least is there a external resource for that?
Try this code,
public class TestActivity extends AppCompatActivity {
int images[] = {R.drawable.ic_earth, R.drawable.oval_btn,
R.drawable.ic_group_black_24dp, R.drawable.ic_earth};
ImagePagerAdapter myAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tests);
ViewPager viewPager = findViewById(R.id.viewPager);
myAdapter = new ImagePagerAdapter(TestActivity.this, images);
viewPager.setAdapter(myCustomPagerAdapter);
setupViewPager(viewPager);
}
int currentPage = 0;
Timer timer;
final long DELAY_MS = 500;
final long PERIOD_MS = 3000;
int NUM_PAGES = 4;
private void setupViewPager(final ViewPager viewPager) {
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
viewPager.setCurrentItem(currentPage++, true);
}
};
timer = new Timer(); // This will create a new Thread
timer .schedule(new TimerTask() { // task to be scheduled
#Override
public void run() {
handler.post(Update);
}
}, DELAY_MS, PERIOD_MS);
}
public class ImagePagerAdapter extends PagerAdapter {
Context context;
int images[];
LayoutInflater layoutInflater;
public ImagePagerAdapter(Context context, int images[]) {
this.context = context;
this.images = images;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return images.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
View itemView = layoutInflater.inflate(R.layout.item, container, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
imageView.setImageResource(images[position]);
container.addView(itemView);
//listening to image click
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
}
}

OnPageChangeListener in ViewPager adapter?

I have a regular ViewPager with an adapter:
public class MyDialogFragment extends DialogFragment {
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private City city;
public static MyDialogFragment newInstance() {
MyDialogFragment fragment = new MyDialogFragment();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_layout, container, false);
viewPager = (ViewPager) v.findViewById(R.id.viewPager);
city = Parcels.unwrap(getArguments().getParcelable("city"));
myViewPagerAdapter = new MyViewPagerAdapter(getContext());
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// Page changed
}
});
return v;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public class MyViewPagerAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
public MyViewPagerAdapter(Context context) {
this.context = context;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.city_layout, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.cityImage);
Glide.with(context)
.load(city.getImage())
.into(imageView);
}
container.addView(view);
return view;
}
#Override
public int getCount() {
return city.size();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == ((View) obj);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
}
As you can see, I have a page change listener set on my ViewPager. But I need to be able to notify the adapter when the page has changed so that I can modify the adapter's ImageView. How can I do this?
Add a method to your adapter class
public class MyViewPagerAdapter extends PagerAdapter {
...
public void pageChanged(int position) {
// Do something
}
...
}
After that in your OnPageChangeListener use that method
#Override
public void onPageSelected(int position) {
myViewPagerAdapter.pageChanged(position);
}
One approach is to create a data structure in your adapter to map the pager view to its position. A SparseArray is most efficient:
private SparseArray<View> pageMap = new SparseArray<>();
Then in the adapter's instantiateItem() method, add the view to the SparseArray:
public Object instantiateItem(ViewGroup container, int position) {
...
pageMap.put(position, view);
...
}
Now in your OnPageChangeListener you can do the following:
#Override
public void onPageSelected(int position) {
View view = adapter.getView(pos);
if (view != null) {
ImageView iv = (ImageView) view.findViewById(R.id.your_image_view);
// You now have the image view
}
}
Make sure you remove views from the SparseArray in the adapter's destroyItem() method:
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
pageMap.remove(position);
...
}
You can use the constructor with imagelist to pass and that automatically called on next page..In your code will be modified like :::
ArrayList imageList=new ArrayList<>();
imageList.add("ImagePath here");
myViewPagerAdapter = new MyViewPagerAdapter(getContext(),imageList);
viewPager.setAdapter(myViewPagerAdapter);
Then your adapter will be like ::
public class MyViewPagerAdapter extends PagerAdapter {
private Context context;
private ArrayList<String> imageList
private LayoutInflater layoutInflater;
public MyViewPagerAdapter(Context context,ArrayList<String> imageList) {
this.context = context;
this.imageList = imageList;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.city_layout, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.cityImage);
Glide.with(context)
.load(imageList.get(position)) // This will be changes like
.into(imageView);
}
container.addView(view);
return view;
}
#Override
public int getCount() {
return city.size();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == ((View) obj);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
That done ..
After this, there are some suggestion that
- please use arraylist while using the viewpager ..
Now you just taking the parceble object from bundle..
you can do the same for the arraylist,
just receive the arraylist from the same bundle by passing the whole arraylist at once.
so you dont need to find the page change event..viewpager will automatically handle that..
Here's How to send & receiving the parceable arraylist
// while sending the list
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("citylist", new ArrayList<City>());
// while receiving the list
ArrayList<City> citylist = getIntent().getParcelableArrayListExtra("citylist");
After this just get the all image and add in the imagelist array
for (int i = 0; i < citylist.size(); i++) {
imageList.add(citylist.get(i).getImage());
}
And pass this imageList in
myViewPagerAdapter = new MyViewPagerAdapter(getContext(),imageList);
viewPager.setAdapter(myViewPagerAdapter);
Tell me if needed more assitance.

ViewPager animation outOfMemoryError

I have 5 SlidingTabs. I want to place ViewPager animation in one of them.
Fragment class:
public class AdFragment extends Fragment {
int[] mResources = {
R.drawable.six,
R.drawable.five,
R.drawable.four,
R.drawable.eight,
R.drawable.one,
R.drawable.two,
R.drawable.three,
R.drawable.seven,
R.drawable.nine,
R.drawable.ten,
};
int currentPage;
public AdFragment() {
// Required empty public constructor
}
Timer swipeTimer;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_ad, container, false);
CustomPagerAdapter mCustomPagerAdapter = new CustomPagerAdapter(getActivity(),mResources);
final ViewPager mViewPager = (ViewPager) view.findViewById(R.id.pager);
mViewPager.setAdapter(mCustomPagerAdapter);
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == mResources.length) {
currentPage = 0;
}
mViewPager.setCurrentItem(currentPage++, true);
}
};
swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, 500, 3000);
return view;
}
}
Adapter class:
class CustomPagerAdapter extends PagerAdapter {
Context mContext;
LayoutInflater mLayoutInflater;
int[] mResources;
private Resources resource;
public CustomPagerAdapter(Context context,int[] mResources) {
mContext = context;
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.mResources = mResources;
}
#Override
public int getCount() {
return mResources.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View itemView = mLayoutInflater.inflate(R.layout.pager_item, container, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
imageView.setImageResource(mResources[position]);
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
#Override
public Object instantiateItem(View view, int position) {
ImageView myView = new ImageView(mContext);
Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), mResources[position]);
myView.setImageBitmap(bitmap);
((ViewPager) view).addView(myView);
return myView;
}
}
At the moment I have 10 images in slideshow.When I open my Tab with Fragment described above, wait for some period, then try to go another Tab and back again to this - I get:
01-27 14:13:53.794 12652-12652/igor.com.totalsoulbeta E/AndroidRuntime: FATAL EXCEPTION: main
Process: igor.com.totalsoulbeta, PID: 12652
java.lang.OutOfMemoryError
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:587)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:422)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:840)
at android.content.res.Resources.loadDrawable(Resources.java:2113)
at android.content.res.Resources.getDrawable(Resources.java:700)
at android.content.res.XResources.getDrawable(XResources.java:521)
at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:323)
at android.support.v7.widget.TintManager.getDrawable(TintManager.java:175)
at android.support.v7.widget.TintManager.getDrawable(TintManager.java:168)
at android.support.v7.widget.AppCompatImageHelper.setImageResource(AppCompatImageHelper.java:51)
at android.support.v7.widget.AppCompatImageView.setImageResource(AppCompatImageView.java:72)
at igor.com.totalsoulbeta.CustomPagerAdapter.instantiateItem(CustomPagerAdapter.java:46)
The size of each image is not more that 150kb. My question is: Is it possible to perfome such animation with 25 images without OutOfMemoryError? If yes, what I need to change in my code? How I can clear heap and where I need to do that?
If it's no the best way of animating, please, advise me your variant
Thanks in advance!
A ViewPager should be able to show any number of pages. At any time it only has 3 pages in memory (unless you change the offscreen page limit). The probleme may lie with the Timer leaking something. The documentation says :
When a timer is no longer needed, users should call cancel(), which
releases the timer's thread and other resources. Timers not explicitly
cancelled may hold resources indefinitely.
Does it help if you add something like that in the Fragment ? :
#Override
public void onDestroyView() {
super.onDestroyView();
swipeTimer.cancel();
swipeTimer = null;
}

Categories

Resources