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);
}
}
Related
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);
}
}
}
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.
I'm trying to replace colors by images from Drawable in this code.
I found this tutorial on how we can make an auto images slider by using viewpager on Android Studio, but this code is to switch colors images how can I replace this colors by images?
Here is my SliderAdapter.java
public class SliderAdapter extends PagerAdapter {
private Context context;
private List<Integer> color;
private List<String> colorName;
public SliderAdapter(Context context, List<Integer> color, List<String> colorName) {
this.context = context;
this.color = color;
this.colorName = colorName;
}
#Override
public int getCount() {
return color.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.item_slider, null);
TextView textView = (TextView) view.findViewById(R.id.textView);
LinearLayout linearLayout = (LinearLayout)
view.findViewById(R.id.linearLayout);
textView.setText(colorName.get(position));
linearLayout.setBackgroundColor(color.get(position));
ViewPager viewPager = (ViewPager) container;
viewPager.addView(view, 0);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager viewPager = (ViewPager) container;
View view = (View) object;
viewPager.removeView(view);
}
}
here is my MainActivity
public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
TabLayout indicator;
List<Integer> color;
List<String> colorName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
viewPager=(ViewPager)findViewById(R.layout.viewPager);
indicator=(TabLayout)findViewById(R.layout.indicator);
color = new ArrayList<>();
color.add(Color.RED);
color.add(Color.GREEN);
color.add(Color.BLUE);
colorName = new ArrayList<>();
colorName.add("RED");
colorName.add("GREEN");
colorName.add("BLUE");
viewPager.setAdapter(new SliderAdapterDemo(this, color, colorName));
indicator.setupWithViewPager(viewPager, true);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new SliderTimer(), 4000, 6000);
}
private class SliderTimer extends TimerTask {
#Override
public void run() {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if (viewPager.getCurrentItem() < color.size() - 1) {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
} else {
viewPager.setCurrentItem(0);
}
}
});
}
}
}
I am writing a simple view pager test app that loads a bunch of data from a website and creates pages to display them.
For the most part the displaying is pretty much all works. However, it falls apart when I load a new set of data to display. When I get a new set, it loads all the data perfectly well however, instead of starting from view 0 it starts at a random location. It could start at the end or somewhere in the middle.
I want all the data to load from page 1, like a book. If you load a new book the book should start from page 1 not a random page.
Reloading calls
I've tried using GotCampDetails() which sets the local variable in the class.
viewPager.setCurrentItem(0);
in my fragment but it doesn't work. Also called notifydatasetchanged() on my adapter, still didn't work.
What am I missing?
public class ViewPagerFragment extends Fragment implements WebReadResultsListener {
private ArrayList<HashMap<String, String>> campDetails;
CustomPagerAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.camp_viewpager, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
if (campDetails != null && ! campDetails.isEmpty()) {
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
adapter = new CustomPagerAdapter(getActivity(), campDetails, viewPager);
viewPager.setAdapter(adapter);
viewPager.setPageTransformer(true, new ZoomOutPageTransformer());
}
}
#Override
public boolean GotCampDetails(ArrayList<HashMap<String, String>> campDetails) {
this.campDetails = campDetails;
return true;
}
#Override
public boolean GotCampList(ArrayList<HashMap<String, String>> campDetails) {
return false;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getFragmentManager().putFragment(outState,"fragmentInstanceSaved",getFragmentManager().findFragmentById(R.id.content));
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Handle orientation changes here
}
}
Adapter:
public class CustomPagerAdapter extends PagerAdapter implements ColorChangeListener {
private ArrayList<HashMap<String, String>> campDetails;
private ViewGroup collection;
private Context mContext;
private boolean isRunning = false;
private ColorChangeListener colorChangeListener;
private int color= pink;
private int currentposition;
private ViewPager viewPager;
public CustomPagerAdapter(Context context, final ArrayList<HashMap<String, String>> campDetails, ViewPager viewPager) {
this.campDetails=campDetails;
this.mContext = context;
this.viewPager = viewPager;
colorChangeListener = (ColorChangeListener) mContext;
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int pos) {
currentposition = pos;
if (campDetails.get(currentposition).get("color").equals("green")) {
color = green;
} else {
color = pink;
}
ColorAppBar(color);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public Object instantiateItem(ViewGroup collection, final int position) {
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.child_item, collection, false);
if (campDetails.size() <= 0) {
Toast.makeText(mContext, "Error in getting camp details", Toast.LENGTH_SHORT).show();
return null;
}
if (campDetails.get(position).get("description").equals("RD") ) {
layout.setBackgroundColor(mContext.getResources().getColor(green));
} else {
layout.setBackgroundColor(mContext.getResources().getColor(pink));
}
collection.addView(layout);
this.collection = collection;
TextView eName = (TextView) layout.findViewById(R.id.en);
TextView nEName= (TextView) layout.findViewById(R.id.nen);
TextView textView6 = (TextView) layout.findViewById(R.id.textView6);
// ImageView nextImg = (ImageView) groupLayout.get(index).findViewById(R.id.nextImg);
eName.setText(campDetails.get(position).get("name"));
if (position+1 < campDetails.size()) {
nEName.setText(campDetails.get(position+1).get("name"));
textView6.setVisibility(View.VISIBLE);
} else {
nEName.setText("You are DONE!!");
textView6.setVisibility(View.INVISIBLE);
}
return layout;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return campDetails.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
return campDetails.get(position).get("name");
}
#Override
public void ColorAppBar(int color) {
colorChangeListener.ColorAppBar(color);
}
}
I finally managed to get it done.
I had to delay the function call setCurrentItem by a few milliseconds. Race condition? I don't know why this is the case but now it works perfectly.
Here is what I added in case someone else may find it useful:
pager.postDelayed(new Runnable() {
#Override
public void run() {
pager.setCurrentItem(pos);
}
}, 100);
I'm having trouble following the details well enough to pinpoint the problem, but this guy seems to have accomplished what you're trying to do: dynamically add and remove view to viewpager
hope it helps
I have image slider in android studio, but images array from inside project.
I want to use images from JSON, how to the best solution..
this is my adapter
public class adapter_image_slider extends PagerAdapter {
Context mContext;
public adapter_image_slider(Context context) {
this.mContext = context;
}
#Override
public int getCount() {
return sliderImagesId.length;
}
private int[] sliderImagesId = new int[]{
R.drawable.imghome1, R.drawable.imghome2, R.drawable.imghome3,
};
#Override
public boolean isViewFromObject(View v, Object obj) {
return v == ((ImageView) obj);
}
#Override
public Object instantiateItem(ViewGroup container, int i) {
ImageView mImageView = new ImageView(mContext);
mImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
mImageView.setImageResource(sliderImagesId[i]);
((ViewPager) container).addView(mImageView, 0);
return mImageView;
}
#Override
public void destroyItem(ViewGroup container, int i, Object obj) {
((ViewPager) container).removeView((ImageView) obj);
}
}
and this is my main activity :
public class activity_img_slider_json extends Fragment {
private static ViewPager mPager;
private static int currentPage = 0;
private static final Integer[] XMEN= {R.drawable.imghome1,R.drawable.imghome2,R.drawable.imghome3,};
private ArrayList<Integer> XMENArray = new ArrayList<Integer>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_img_slider_json,null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
super.onCreate(savedInstanceState);
init();
}
private void init() {
for(int i=0;i<XMEN.length;i++)
XMENArray.add(XMEN[i]);
mPager = (ViewPager)getActivity().findViewById(R.id.pager);
mPager.setAdapter(new adapter_img_slider_json(getActivity(), XMENArray));
CircleIndicator indicator = (CircleIndicator)getActivity().findViewById(R.id.indicator);
indicator.setViewPager(mPager);
// Auto start of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == XMEN.length) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
}
}
Thanks For Attention.