Skip to main content

How to Create Image Slider with Page Indicator

Image slider are used in almost every Android Application .In this post we will Learn about Creating Image Slider with page Indicator.So lets start with Coding part:-


First of all we need to add this library in our build.gradle file

compile 'com.squareup.picasso:picasso:2.3.3'

Step 1:

activity_main.xml

 <RelativeLayout  
 android:layout_width="match_parent"  
 android:layout_height="200dp">  
 <android.support.v4.view.ViewPager  
 android:id="@+id/vp_slider"  
 android:layout_width="match_parent"  
 android:layout_height="match_parent" />  
 <LinearLayout  
 android:id="@+id/ll_dots"  
 android:layout_width="match_parent"  
 android:layout_height="30dp"  
 android:layout_alignParentBottom="true"  
 android:layout_marginBottom="20dp"  
 android:gravity="center"  
 android:orientation="horizontal"></LinearLayout>  
 </RelativeLayout>  

Create the layout for viewpager item

layout_slider.xml

 <?xml version="1.0" encoding="utf-8">  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:orientation="vertical" android:layout_width="match_parent"  
   android:layout_height="match_parent">  
   <ImageView  
     android:id="@+id/im_slider"  
     android:layout_width="match_parent"  
     android:layout_height="match_parent"  
     android:scaleType="centerCrop"/>  
 </LinearLayout>  

Step 2:

SliderPagerAdapter.java

 public class SliderPagerAdapter extends PagerAdapter {  
 private LayoutInflater layoutInflater;  
   Activity activity;  
   ArrayList<String> image_arraylist;  
   public SliderPagerAdapter(Activity activity, ArrayList<String> image_arraylist) {  
     this.activity = activity;  
     this.image_arraylist = image_arraylist;  
   }  
   @Override  
   public Object instantiateItem(ViewGroup container, int position) {  
     layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
     View view = layoutInflater.inflate(R.layout.layout_slider, container, false);  
     ImageView im_slider = (ImageView) view.findViewById(R.id.im_slider);  
     Picasso.with(activity.getApplicationContext())  
         .load(image_arraylist.get(position))  
         .placeholder(R.mipmap.ic_launcher) // optional  
         .error(R.mipmap.ic_launcher)     // optional  
         .into(im_slider);  
     container.addView(view);  
     return view;  
   }  
   @Override  
   public int getCount() {  
     return image_arraylist.size();  
   }  
   @Override  
   public boolean isViewFromObject(View view, Object obj) {  
     return view == obj;  
   }  
   @Override  
   public void destroyItem(ViewGroup container, int position, Object object) {  
     View view = (View) object;  
     container.removeView(view);  
   }  
 }  

and Finally the MainActivity.java

 public class MainActivity extends AppCompatActivity{  
   private ViewPager vp_slider;  
   private LinearLayout ll_dots;  
   SliderPagerAdapter sliderPagerAdapter;  
   ArrayList<String> slider_image_list;  
   private TextView[] dots;  
   int page_position = 0;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
    
     setContentView(R.layout.activity_main);   
     init();  

     addBottomDots(0);  
     final Handler handler = new Handler();  
     final Runnable update = new Runnable() {  
       public void run() {  
         if (page_position == slider_image_list.size()) {  
           page_position = 0;  
         } else {  
           page_position = page_position + 1;  
         }  
         vp_slider.setCurrentItem(page_position, true);  
       }  
     };  
     new Timer().schedule(new TimerTask() {  
       @Override  
       public void run() {  
         handler.post(update);  
       }  
     }, 100, 5000);  
   }  
   private void init() {  
    
     vp_slider = (ViewPager) findViewById(R.id.vp_slider);  
     ll_dots = (LinearLayout) findViewById(R.id.ll_dots);  
     slider_image_list = new ArrayList<>();  
     slider_image_list.add("http://imageurl.com/images/image1.jpg");  
     slider_image_list.add("http://imageurl.com/images/image2.jpg");  
     
     sliderPagerAdapter = new SliderPagerAdapter(MainActivity.this, slider_image_list);  
     vp_slider.setAdapter(sliderPagerAdapter);  
     vp_slider.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {  
       @Override  
       public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {  
       }  
       @Override  
       public void onPageSelected(int position) {  
         addBottomDots(position);  
       }  
       @Override  
       public void onPageScrollStateChanged(int state) {  
       }  
     });  
   }  
   private void addBottomDots(int currentPage) {  
     dots = new TextView[slider_image_list.size()];  
     ll_dots.removeAllViews();  
     for (int i = 0; i < dots.length; i++) {  
       dots[i] = new TextView(this);  
       dots[i].setText(Html.fromHtml("&#8226;"));  
       dots[i].setTextSize(35);  
       dots[i].setTextColor(Color.parseColor("#000000"));  
       ll_dots.addView(dots[i]);  
     }  
     if (dots.length > 0)  
       dots[currentPage].setTextColor(Color.parseColor("#FFFFFF"));  
   }  
 }  

that's all for dynamic image slider its look like this

but sometimes we required padding left and right in images for this we add few lines of code in our viewpager

<android.support.v4.view.ViewPager  
 android:id="@+id/vp_slider"  
 android:layout_width="match_parent"  
 android:layout_height="match_parent"
android:clipToPadding="false"
android:paddingLeft="30dp"
android:padiingRight="30dp"
/> 

and after adding these lines our image slider looks like this

Thank you !! Keep coding and Keep Sharing.


Comments

Popular posts from this blog

How to Download Apk file from Url and Install Programmatically

In this post we learn about download apk file from server or website and then install it Programmatically in Phone. Sometimes we have to download external apk file from server and then install if downloading successfully finished.For this we use AsyncTask class  for background process. So here is Code Snippet for this task.Lets Start :- Before this we have to add these Permissions in Manifest.xml file : <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> DownloadNewVersion.java class DownloadNewVersion extends AsyncTask<String,Integer,Boolean> { @Override protected void onPreExecute() { super.onPreExecute(); bar = new ProgressDialog(getActivity()); bar.setCancelable(false); bar.setMessage("Downl...

Auto read OTP using SMS User Consent API in Android

Some times ago Google Play restricts the use of high risk or sensitive permissions, including the SMS or Call Log permission groups. It means you have to justify why you are taking SMS or other high risk or sensitive permissions for your application .For this you may be required to complete the Permissions Declaration Form and receive approval from Google Play. Before this every app even who does not have any purpose for taking SMS or other high sensitive permissions in their app ,They was taking these permissions from users and this is a kind of security beach.  For solution of this problem Google introduce SMS User Consent API . The SMS User Consent API complements the SMS Retriever API by allowing an app to prompt the user to grant access to the content of a single SMS message. When a user gives consent, the app will then have access to the entire message body to automatically complete SMS verification. If your appeal for SMS permission is rejected by Google team you can u...

How to open pdf file url using webview in Android

 Sometimes we have requirement of showing pdf file in our Android Application. Although there are many third party gradle dependencies available online by which you can show your pdf file easily but one of the major drawback of using these libraries are they will increase you apk size .In some cases they will increase apk size upto ~14 MB. Alternatively you can access and show pdf file using assets and from storage options. This can take less size than any third party library. Here we use pdf using url and if you directly open your pdf file url in webview you will get no result because it will start downoad if you open this link in any web browser.  So in this article we will learn how we can open our pdf url using webview and without using any third party library. So lets Start step by Step:- Lets Suppose you have a pdf file url something like   http://yourwebsite.com/files/mydocumentfile.pdf Step 1: So we you this pdf file url to embed in our webview .First of all you h...