I am trying to implement the automatic image slide using View Pager. I used handler to slide the images one after another for certain interval (like 10 seconds). This is my code please tell me where i am doing wrong.
public class MainActivity extends Activity {
ViewPager mViewPager;
CustomPagerAdapter mCustomPagerAdapter;
private final Handler handler = new Handler();
static int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCustomPagerAdapter = new CustomPagerAdapter(this);
mViewPager = (ViewPager) findViewById(R.id.pager);
Runnable runnable = new Runnable() {
#Override
public void run() {
for (int i = 0; i < mCustomPagerAdapter.getCount()-1; i++) {
final int value = i;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
mViewPager.setCurrentItem(value, true);
mViewPager.setAdapter(mCustomPagerAdapter);
}
});
}
}
};
new Thread(runnable).start();
// mViewPager.setAdapter(mCustomPagerAdapter);
}
}
class CustomPagerAdapter extends PagerAdapter{
Context mContext;
LayoutInflater mLayoutInflater;
int[] mResources = {
R.drawable.splash0,
R.drawable.splash1,
R.drawable.splash2,
R.drawable.splash3,
R.drawable.splash0,
R.drawable.splash2
};
public CustomPagerAdapter(Context context) {
mContext = context;
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#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);
}
}
Try this it works great
mIntroPagerAdapter = new mIntroPagerAdapter(this);
mIntroViewPager = (ViewPager) findViewById(R.id.pager);
mIntroViewPager.setAdapter(mIntroPagerAdapter );
static int i=0;
private final Handler handler = new Handler();
void setImageMove()
{
handler.post(ViewPagerVisibleScroll);
}
Runnable ViewPagerVisibleScroll= new Runnable() {
#Override
public void run() {
if(i <= mIntroPagerAdapter.getCount()-1)
{
mIntroViewPager.setCurrentItem(i, true);
handler.postDelayed( ViewPagerVisibleScroll, 10000);
i++;
}
}
};
Call this method pageSwitcher
int page = 0;
pageSwitcher(10); 10 Seconds
public void pageSwitcher(int seconds)
{
timer = new Timer(); // At this line a new Thread will be created
timer.scheduleAtFixedRate(new RemindTask(), 0, seconds * 1000);
// delay in milliseconds
}
class RemindTask extends TimerTask
{
#Override
public void run()
{
runOnUiThread(new Runnable()
{
public void run()
{
if (page > mResources .size()-1)
{
page=0;
}
else
{
viewPager.setCurrentItem(page++,true);
}
}
});
}
}
}
new Timer().schedule(new TimerTask() {
#Override
public void run() {
if (index < mCustomPagerAdapter.getCount()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mViewPager.setCurrentItem(index, true);
index++;
}
});
} else {
this.cancel();
}
}
}, 10000, 10000);
There is an Autoscroll ViewPager library.
If you need just sliding images then AndroidImageSlider might be more convenient. I've used it and it does the job perfectly.
Actually, you can get the idea how to implement AutoScrollViewPager:scrollOnce() sliding from those libraries.
Related
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);
}
}
I add to my app ViewPager to display a set of images I get the image from database.It works fine but I need to work (Intent) to image.So where user click on image he should go to a new activity and see that picture in it.I searched for a solution and could not find the solution.
If anyone Knew the solution help me please.
public class ViewPagerAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
private List<SliderUtils> sliderImg;
private ImageLoader imageLoader;
public ViewPagerAdapter(List sliderImg,Context context) {
this.sliderImg = sliderImg;
this.context = context;
}
#Override
public int getCount() {
return sliderImg.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.custom_layout, null);
SliderUtils utils = sliderImg.get(position);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
imageLoader.get(utils.getSliderImageUrl(), ImageLoader.getImageListener(imageView, R.mipmap.ic_launcher_round, android.R.drawable.ic_dialog_alert));
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(position == 0){
Toast.makeText(context, "Slide 1 Clicked", Toast.LENGTH_SHORT).show();
} else if(position == 1){
Toast.makeText(context, "Slide 2 Clicked", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Slide 3 Clicked", Toast.LENGTH_SHORT).show();
}
}
});
ViewPager vp = (ViewPager) container;
vp.addView(view, 0);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}
public class FoodFregmaent extends Fragment {
ViewPager viewPager;
LinearLayout sliderDotspanel;
private int dotscount;
private ImageView[] dots;
RequestQueue rq;
List<SliderUtils> sliderImg;
ViewPagerAdapter viewPagerAdapter;
String request_url = "http://===========sliedshow.php";
public FoodFregmaent() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_food_fregmaent, container, false);
rq = CustomVolleyRequest.getInstance(getContext()).getRequestQueue();
sliderImg = new ArrayList<>();
viewPager = (ViewPager) view.findViewById(R.id.viewPager);
sliderDotspanel = (LinearLayout)view. findViewById(R.id.SliderDots);
sendRequest();
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for(int i = 0; i< dotscount; i++){
dots[i].setImageDrawable(ContextCompat.getDrawable(getContext().getApplicationContext(), R.drawable.nonactive_dot));
}
dots[position].setImageDrawable(ContextCompat.getDrawable(getContext().getApplicationContext(), R.drawable.active_dot));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
return view;
}
public void sendRequest(){
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, request_url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for(int i = 0; i < response.length(); i++){
SliderUtils sliderUtils = new SliderUtils();
try {
JSONObject jsonObject = response.getJSONObject(i);
sliderUtils.setSliderImageUrl(jsonObject.getString("imageurl"));
} catch (JSONException e) {
e.printStackTrace();
}
sliderImg.add(sliderUtils);
}
viewPagerAdapter = new ViewPagerAdapter(sliderImg, getActivity());
viewPager.setAdapter(viewPagerAdapter);
dotscount = viewPagerAdapter.getCount();
dots = new ImageView[dotscount];
for(int i = 0; i < dotscount; i++){
dots[i] = new ImageView(getActivity());
dots[i].setImageDrawable(ContextCompat.getDrawable(getContext().getApplicationContext(), R.drawable.nonactive_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
sliderDotspanel.addView(dots[i], params);
}
dots[0].setImageDrawable(ContextCompat.getDrawable(getContext().getApplicationContext(), R.drawable.ic_launcher_background));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
CustomVolleyRequest.getInstance(getContext()).addToRequestQueue(jsonArrayRequest);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new MyTimerTask(), 2000, 4000);
}
public class MyTimerTask extends TimerTask {
#Override
public void run() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if(viewPager.getCurrentItem() == 0){
viewPager.setCurrentItem(1);
} else if(viewPager.getCurrentItem() == 1){
viewPager.setCurrentItem(2);
} else {
viewPager.setCurrentItem(0);
}
}
});
}
}
}
public class SliderUtils {
String imageurl;
public String getSliderImageUrl() {
return imageurl;
}
public void setSliderImageUrl(String imageurl) {
this.imageurl = imageurl;
}
}
Still I search about solution to it
You can add an Intent with a String that contains the image URL into your view.setOnClickListener within the instantiateItem() of the ViewPager
#Override
public Object instantiateItem(ViewGroup container, final int position) {
// ... Other code is omitted
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), Activity2.class); // Change the name of the other activity
intent.putExtra("url", sliderImg.get(position).getSliderImageUrl()); // add the image URL to the other activity
}
});
And at the target activity, receive the url with
String url = getIntent().getStringExtra("url")
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);
}
}
}
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.
I'm using viewpager library to implement image slider but don't know how to implement it to auto scroll. here is my code.
ViewPagerAdapter.java
public class ViewPagerAdapter extends FragmentPagerAdapter implements IconPagerAdapter{
private int[] Images = new int[] { R.drawable.viewpager, R.drawable.viewpager,
R.drawable.viewpager, R.drawable.viewpager,R.drawable.viewpager, R.drawable.viewpager
};
protected static final int[] ICONS = new int[] { R.drawable.logo,
R.drawable.logo, R.drawable.logo, R.drawable.logo,R.drawable.logo, R.drawable.logo };
private int mCount = Images.length;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new SliderFragment(Images[position]);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mCount;
}
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
SliderFragment.java
public class SliderFragment extends SherlockFragment {
int imageResourceId;
public SliderFragment(int i) {
imageResourceId = i;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ImageView image = new ImageView(getActivity());
image.setImageResource(imageResourceId);
LinearLayout layout = new LinearLayout(getActivity());
layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
layout.setGravity(Gravity.CENTER);
layout.addView(image);
return layout;
}
}
MainActivity.java
mAdapter = new ViewPagerAdapter(getSupportFragmentManager());
vPager = (ViewPager) findViewById(R.id.pager);
pIndicator = (PageIndicator) findViewById(R.id.indicator);
vPager.setAdapter(mAdapter);
pIndicator.setViewPager(vPager);
((CirclePageIndicator) pIndicator).setSnap(true);
Please guide me how can i implement it with auto scroll so that images are scrolling automatically after the predefined time.
page=0;
timer=new TimerTask() {
#Override
enter code here
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
viewPager.setCurrentItem(page % 4); // 4= no. of page in viewpager
page++;
}
});
}
};
Timer time=new Timer();
time.schedule(timer, 0, 3000); //3000 millisecond for replace the viewpager page
I Solved it using the timer thread. After specific time i change the view pager image which become the auto scroll.