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.
Related
I have implemented an image slider with dots. Working perfectly. Slider is working only on manual by sliding from finger left or right not automatically by a time interval 3 seconds.
See the code and suggest me some approach to working slider automatically.
ViewPager in .xml layout file
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="160dp"
android:layout_alignParentTop="true" />
<LinearLayout
android:paddingTop="8dp"
android:id="#+id/slider_dots"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal|center_vertical"
android:layout_below="#id/view_pager"></LinearLayout>
</RelativeLayout>
And here's ViewPageAdapter java class
public class ViewPagerAdapter extends PagerAdapter {
Context context;
LayoutInflater layoutInflater;
int images[] = {R.mipmap.banner, R.mipmap.banner1, R.mipmap.banner2, R.mipmap.banner3, R.mipmap.banner4, R.mipmap.banner5};
public ViewPagerAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
return images.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.slider_banner_layout, null);
ImageView imageView = view.findViewById(R.id.image_view_banner_image);
imageView.setImageResource(images[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);
}
}
MainActivity.java
public class HomeActivity extends AppCompatActivity {
ViewPager viewPager;
LinearLayout sliderDotsPanel;
ImageView[] dots;
private int dotCount;
ViewPagerAdapter viewPagerAdapter;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = findViewById(R.id.app_bar);
toolbar.setTitle("");
toolbar.setLogo(R.mipmap.toolbar_logo);
setSupportActionBar(toolbar);
viewPager = findViewById(R.id.view_pager);
viewPagerAdapter= new ViewPagerAdapter(this);
viewPager.setAdapter(viewPagerAdapter);
sliderDotsPanel=findViewById(R.id.slider_dots);
initializeDots();
}
private void initializeDots() {
dotCount = viewPagerAdapter.getCount();
dots = new ImageView[dotCount];
for (int i = 0; i < dotCount; i++) {
dots[i] = new ImageView(this);
dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.non_active_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(getApplicationContext(), R.drawable.active_dot));
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 < dotCount; i++) {
dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.non_active_dot));
}
dots[position].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dot));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
I will show you how to make it slide, one page after the other and then stop:
private void slideAutomatically(final long milliSeconds){
new Thread(new Runnable(){
#Override
public void run(){
for(int i = 0 ; i<6 ; i++){
//sleep
try{
Thread.sleep(milliSeconds);
}catch(InterruptedException e){
}
//change position
runOnUiThread(new Runnable(){
#Override
public void run(){
viewPager.setCurrentItem(i);}
});
}
}
}).start();
}
Call this method whenever you want the pages to slide automatically:
//lets say I want the pages to change every 3 seconds
slideAutomatically(3000);
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 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.
I have a viewpager with image fragments in it that works but on back was getting an error saying that there is no empty constructor. I made one but now my images don't show up because imageResourceId is null. I've tried a million things and can't figure it out.
public final class TestFragment extends Fragment {
String imageResourceId;
public TestFragment() {
}
public TestFragment(String cONTENT) {
imageResourceId = cONTENT;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ImageView image = new ImageView(getActivity());
new DownloadImageTask((ImageView) image).execute(imageResourceId);
LinearLayout layout = new LinearLayout(getActivity());
layout.setGravity(Gravity.CENTER);
layout.addView(image);
return layout;
}
}
class TestFragmentAdapter extends FragmentPagerAdapter implements
IconPagerAdapter {
public String[] CONTENT;
private int mCount;
protected static final int[] ICONS = new int[] {
R.drawable.perm_group_calendar, R.drawable.perm_group_camera,
R.drawable.perm_group_device_alarms, R.drawable.perm_group_location };
public TestFragmentAdapter(FragmentManager fm, JSONArray photoData) {
super(fm);
// photoData = (JSONArray) userProfile.get("photos");
CONTENT = new String[photoData.length()];
mCount = photoData.length();
for (int i = 0; i < photoData.length(); i++) {
JSONObject mainPhoto;
try {
mainPhoto = photoData.getJSONObject(i);
CONTENT[i] = mainPhoto.getString("src_big");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
notifyDataSetChanged();
}
#Override
public Fragment getItem(int position) {
return new TestFragment(CONTENT[position]);
}
#Override
public int getCount() {
return mCount;
}
#Override
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
in the activity
mAdapter = new TestFragmentAdapter(
getSupportFragmentManager(), photoData);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (LinePageIndicator) findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
Android uses the empty constructor of a fragment to restore the fragment when there is a configuration change, that's why you can't modify it, and you can't override it because you get an error in eclipse. The best practice to pass arguments to a fragment, when instantiating it, is to use an static factory method:
public class TestFragment extends Fragment {
String imageResourceId;
public static TestFragment newInstance(String resource) {
TestFragment f = new TestFragment();
Bundle args = new Bundle();
args.putString("Resource", resource);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imageResourceId = getArguments().getString("Resource");
}
}
To instanciate it you use the static method:
TestFragment fragment = TestFragment.newInstance("some string");
in My root Activity i have Slide show that displayed by the VIewPager .
in my case i want to open new activity or dialog box or something like this when i pressed image on Slide show .
Normally i used OnclickListener and assign picture id to it and don't get any Feedback .
RootActivity.java
public class RootActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_root);
// Image slide show
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(0);
ImageAdapter.setTimer(viewPager, 3, 0);
// End Image slide show
ViewPager vp = (ViewPager)findViewById(R.drawable.ax1);
vp.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
System.out.print("OK ...");
}
});
}
}
ImageAdapter.java
public class ImageAdapter extends PagerAdapter {
final static Handler handler = new Handler();
public static Timer swipeTimer ;
Context context;
private int[] GalImages = new int[] {
R.drawable.one,
R.drawable.two,
R.drawable.three,
R.drawable.ax1,
R.drawable.ax2,
};
ImageAdapter(Context countDownTimer){
this.context=countDownTimer;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
public static void setTimer(final ViewPager myPager, int time, final int curPage){
final Runnable Update = new Runnable() {
int NUM_PAGES =5;
int currentPage = curPage ;
public void run() {
if (currentPage == NUM_PAGES ) {
currentPage = 0;
}
myPager.setCurrentItem(currentPage++, true);
}
};
swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, 1000, time*1000);
}
}
Okay, first things first...
1. This line, in RootActivity.onCreate() does not make a lot of sense:
ViewPager vp = (ViewPager)findViewById(R.drawable.ax1);
You're trying to find a ViewPager object in the layout using a drawable resource id. So delete this line and everything in onCreate() that comes after it.
2. You can only attach an OnClickListener to an existing view and since there is no OnItemClickListener for PagerAdapters, you need to attach the OnClickListener to the appropriate Views from within the Adapter's instantiateItem() method.
I have attached a modified version of your code representing these points.
RootActivity.java
public class RootActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_root);
// Image slide show
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(0);
ImageAdapter.setTimer(viewPager, 3, 0);
// End Image slide show
}
}
ImageAdapter.java
Look for the // Begin Added by SpaceLord comments
public class ImageAdapter extends PagerAdapter {
final static Handler handler = new Handler();
public static Timer swipeTimer;
Context context;
private int[] GalImages = new int[]{
R.drawable.one,
R.drawable.two,
R.drawable.three,
R.drawable.ax1,
R.drawable.ax2,
};
ImageAdapter(Context countDownTimer) {
this.context = countDownTimer;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(GalImages[position]);
// Begin Added by SpaceLord
imageView.setOnClickListener(itemClickListener);
imageView.setTag(position);
// End Added by SpaceLord
container.addView(imageView, 0);
return imageView;
}
// Begin Added by SpaceLord
private final View.OnClickListener itemClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
final int tag = (Integer) v.getTag();
switch (tag) {
// Do whatever you need to for each slide click here
case 0:
Log.d(ImageAdapter.class.getSimpleName(), "Clicked on ONE");
break;
case 1:
Log.d(ImageAdapter.class.getSimpleName(), "Clicked on TWO");
break;
case 2:
Log.d(ImageAdapter.class.getSimpleName(), "Clicked on THREE");
break;
case 3:
Log.d(ImageAdapter.class.getSimpleName(), "Clicked on AX1");
break;
case 4:
Log.d(ImageAdapter.class.getSimpleName(), "Clicked on AX2");
break;
}
}
};
// End Added by SpaceLord
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((ImageView) object);
}
public static void setTimer(final ViewPager myPager, int time, final int curPage) {
final Runnable Update = new Runnable() {
int NUM_PAGES = 5;
int currentPage = curPage;
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
myPager.setCurrentItem(currentPage++, true);
}
};
swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, 1000, time * 1000);
}
}
Directly set onClickListener(...) to your ImageView in your ImageAdapter like:
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(GalImages[position]);
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
//Do your job
}
});
((ViewPager) container).addView(imageView, 0);
return imageView;
}