Custom View - HorizontalSlider


SDK Version: 
M5

Introduction

In this tutorial we'll create a custom View called HorizontalSlider based on ProgressBar. This slider will allow the user to move the slider back and forth on the screen and get notified when this happens.

Click here to download the complete source.

Creating an interface

First think we'll want to do is create an interface to use to notify our Activities when a user changes the value of the slider. We'll call this interface OnProgressChangeListener to match the naming conventions of some of the other interfaces used in Android. Here is our interface:

  1. public interface OnProgressChangeListener {
  2.         void onProgressChanged(View v, int progress);
  3. }

Interfaces do not do anything, they just create an outline that you must use to implement an object later.

Creating the view

Creating the view in this case is very easy. All that we must do is create a class that extends ProgressBar. After we create this class we will just need to override the constructors and the onMotionEvent() method.

Tip:To override the constructors in Eclipse you can right click in the class's block and hit Source->Generate Constructors from Superclass

All that we must do in the constructors is set our progress bar's background to be the progress_horizontal drawable that is built into android, this will make it a horizontal progress bar instead of the circular one.

Here is the HorizontalSlider class:

  1. public class HorizontalSlider extends ProgressBar {
  2.  
  3.         private OnProgressChangeListener listener;
  4.  
  5.         private static int padding = 2;
  6.  
  7.         public interface OnProgressChangeListener {
  8.                 void onProgressChanged(View v, int progress);
  9.         }
  10.        
  11.         public HorizontalSlider(Context context, AttributeSet attrs,
  12.                         Map inflateParams, int defStyle) {
  13.                 super(context, attrs, inflateParams, defStyle);
  14.         }
  15.  
  16.         public HorizontalSlider(Context context, AttributeSet attrs,
  17.                         Map inflateParams) {
  18.                 super(context, attrs, inflateParams, android.R.attr.progressBarStyleHorizontal);
  19.  
  20.         }
  21.  
  22.         public HorizontalSlider(Context context) {
  23.                 super(context);
  24.  
  25.         }
  26.  
  27.         public void setOnProgressChangeListener(OnProgressChangeListener l) {
  28.                 listener = l;
  29.         }
  30.  
  31.         @Override
  32.         public boolean onTouchEvent(MotionEvent event) {
  33.  
  34.                 int action = event.getAction();
  35.  
  36.                 if (action == MotionEvent.ACTION_DOWN
  37.                                 || action == MotionEvent.ACTION_MOVE) {
  38.                         float x_mouse = event.getX() - padding;
  39.                         float width = getWidth() - 2*padding;
  40.                         int progress = Math.round((float) getMax() * (x_mouse / width));
  41.  
  42.                         if (progress < 0)
  43.                                 progress = 0;
  44.  
  45.                         this.setProgress(progress);
  46.  
  47.                         if (listener != null)
  48.                                 listener.onProgressChanged(this, progress);
  49.  
  50.                 }
  51.  
  52.                 return true;
  53.         }
  54. }

First we include our interface as a member class of this view. Then we setup the 3 constructors, having the second one pass in a style for the horizontal progress bar.

Next we create a function setOnProgressChangeListener() so that when you use this code you can use the interface created above to monitor changes in the progress level. We'll save this to our private variable named "listener".

Now, all the work happens starting on line 42 in our onTouchEvent() class. This class is notified when the user is clicking or dragging a click.

This method is pretty simple, we just calculate what the progress is based on the width of the progress bar and the x value for the click. I have created a static paddedPixels variable that will offset our clicks and widths because there is about 2 pixels of unused space on each side of the bar.

After we set our progress we can also call our OnProgressChangeListener's onProgressChanged() method to notify interested parties that the progress has changed.

On the next page we'll figure out how to use this new object.

Using HorizontalSlider

You can use HorizontalSlider just like any ProgressBar. In this example I'm going to utilize the new ProgresBar that is built into the title of the application and a HorizontalSlider. When the user clicks to change the HorizontalSlider value I'll update the ProgressBar in the title to show that it's working. Here is the main.xml layout I've used for this example:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.         android:layout_width="fill_parent"
  4.         android:layout_height="fill_parent"
  5.         android:paddingLeft="10dip"
  6.         android:paddingRight="10dip"
  7.         android:paddingTop="100dip"
  8.         android:gravity="center_horizontal" >
  9.  
  10.         <com.helloandroid.android.horizontalslider.HorizontalSlider
  11.                 android:id="@+id/slider"
  12.                 android:layout_width="250dip"
  13.                 android:layout_height="20dip"
  14.                 android:max="10000"
  15.                 android:layout_centerHorizontal="true" />
  16.    
  17. </LinearLayout>

Now, we can create a simple Activity for this layout. Here is SliderTest.java:

  1. public class SliderTest extends Activity {
  2.  
  3.         private HorizontalSlider slider;
  4.  
  5.         @Override
  6.         public void onCreate(Bundle icicle) {
  7.                 super.onCreate(icicle);
  8.  
  9.                 requestWindowFeature(Window.FEATURE_PROGRESS);
  10.                 setContentView(R.layout.main);
  11.                 setProgressBarVisibility(true);
  12.  
  13.                 slider = (HorizontalSlider) this.findViewById(R.id.slider);
  14.                 slider.setOnProgressChangeListener(changeListener);
  15.         }
  16.  
  17.         private OnProgressChangeListener changeListener = new OnProgressChangeListener() {
  18.  
  19.                 public void onProgressChanged(View v, int progress) {
  20.                         setProgress(progress);
  21.                 }
  22.  
  23.         };
  24. }

In our onCreate() function we request that the title progress bar feature is enabled with the requestWindowFeature() method. Then all we have to do is create a OnProgressChangeListener for the slider and update the progress bar from there!

You can do anything you want with custom views, in this case it was a very simple change to a built in view, but don't limit yourself to the ones that were handed to us.

Good luck!

Comments

really thanksss!!!!
My blog l My product

thank's bro,, this is very useful!

behel lepas pasang

I am really enjoying reading your well written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work.
Best Running Shoes For Women

nice blog and nice post! it's really useful

heavenrooms.com | 5770 benchmark

Impressive, it works a treat.
A bit fidly but you get the results.
duke peterson

I'll be visiting your site again to gather some more valuable information.

My blog : Web Design Miami | Miami Web Design

Contact people you care about before timberland mens boots. You are a person with feelings and relocating overseas is a big event. Talk to your close friends and family about your thoughts, dreams and fears for your new venture before you leave timberland women boots and make sure you keep in regular contact after you arrive and during your time away. Sharing the experience always halves any burdens and doubles the excitement of timberland 6 inch boots sale any achievements. Besides, with the ease and convenience of communicating via the Internet nowadays, there is no excuse not to keep in touch! It is important to realize that timberland 3 eyes burgundy while new and exciting things may be happening to you in your new environment, things and people back at home will also be changing. It is possible to feel isolated and timberland waterproof boots experience "reverse culture shock" when you return home for a visit after an extended period of time away. The extent of this can be determined by such things as how involved you become in your new culture and how involved timberland mens boots stay in your original culture. Remember your roots, they are an important part of who you are. Learn from all experiences. Value both your roll top timberlands achievements and disappointments as learning experiences that can be applied to future situations in life. Value all positive outcomes and more importantly, don't take negative outcomes at face value timberland mens chukka. Instead, try to see the lessons in mistakes and turn them into opportunities for future improvement. Opportunities are present all timberland shoes store, but often they go by unnoticed. Recognizing opportunities is a skill which anyone can learn through practice and patience. In summary, travelling overseas is an amazing opportunity for timberland 14 inch boots growth, which not everyone has the chance, or the inclination to take part in. By no means should my advice be taken as the only timberland mens roll top to do things. QL

Mens Timberland Roll-Top Boot-Wheat Black

timberland for sale
uk timberland boots
timberland work boots

was able to find the details that I was searching for. I would like to thank you for the initiatives you have made in writing this article. I am hoping the same best efforts from you in the future as well. Actually your inventive writing skills has inspired me a lot.All these post are always inspiring and I like to read quality article so I am happy to get many good points here in the post, writing is really good. how to get your ex back | snoring solutions

Will give it a try
Custom logo design

Nice Share..
Masariq Blog

I am really inspired from your blog, I must say you have done a terrific job.
escuelas de ingles df

Really Really Thanks For This Wonderful article.This article was very usefull for Android owner, thanks for share...

mediafire movies | mediafire mkv movie

Thank you - the site very very nice

المجتمع المصري هو مجتمع يحب الترفية حيث ان سكان مصر تصل الى تسعون مليون فرد ولذلك نحن نقدم خدمة دردشة مصرية لكل اهل مصر ام الدنيا , وتعتبر مصر متقدمة فى هذا العالم من حيث النمو فى مجالات التكنولوجيا و الكمبيوتر بنسبة كبيرة جدا لذلك نفضل دخول شات مصري اكبر تجمع بنات و شباب فى شات الحب و اجمل بنات فى دردشة دردشة الحب , اضافة الى ذلك حيث يوجد دردشة قوية تضم جميع محافظات مصر هي شات مصرية الكتابية نتمني لكم قضاء وقت ممكن فى شات الاصدقاء و احلي دردشة التعارف الذي يوجد به بنات رومانسية فى دردشة بنات مصر المصرية


شات الحب - دردشة مصرية - شات - شات مصري - شات حب - دردشة - دردشة كتابية - دردشة الحب - شات حبنا - شات حبي - شات مصرية - دردشة حب - شات بنات - دردشة مصر - دردشة بنات مصر - شات بنات مصر - شات صوتي - chat love - دردشة ياحبي - شات بنات لبنان - الحب - شات كتابي - منتدي ياحبي - شات مصر - دردشة حبنا - العاب تلبيس البنات - دردشة بنات - شات ياحبي - Chat - شات لبناني - شات كلامنجي - دردشة كلامنجي - شبكة - تصميم مواقع - تصميم - شات الاسكندرية - دردشة لبنانية - دردشة بنات لبنان - بنات لبنان - موقع شات - سعودي كول - شات سعودي كول - شات بنت مصر - شات سكس

This excellent written piece is undoubtedly outstanding. This information is undoubtedly what I had to have and additionally it is educative. Superb. download movies

I liked the theme of this blog and the fact that the content provided is pretty nice. Will come back to read more..Buy Backlinks

Large addict from this site, several your blog posts have truly helped me out. ... We appreciate for posting this post, we saw a couple other similar posts but yours was the best so far. we hope it stays updated,You've very simple and attractive attitude, nice wrork and awesome site........

cell phone spyware

Android has a lot of advantages if the kits compare with other smart phones. Your design is very nice and attractive, it may be appropriate if I use. pheromone cologne

I gained a bunch of excellent solutions as a result of looking at this. This short post has a couple of awesome important facts. Wonderful. movie downloads

thank you for information

حجز فنادق مكة
فنادق مكة

Android apps are surely dominating the market nowadays and surely theres a reason behind it as to why
Melbourne Botox

nice article !! Optimasi SEO

This is one of the best post that I had ever read on web of this topic. You have done an excellent job here by posting such an informative post. Keep sharing buddy...

Regards,

banners

It is good to see some detailed information on this topic which is very rarely discussed on the internet. Thanks for this pretty useful share. Windows 8

i like this kaminomoto and for this info bro kaminomoto,penumbuh rambut

Really Really Thanks For This Wonderful article. Its glad that nowadays also, there is some original content on the internet. Otherwise, everywhere you go you will find duplicate content. Thanks Again. Like to Read You article and blog.

movie download | mediafire links | all buzzy news |

the information in this blog is very interesting
old tv shows

Very interesting information, please add some
old tv shows

I would like to thank you for the initiatives you have made in writing this article. I am hoping the same best efforts from you in the future as well. Actually your inventive writing skills has inspired me a lot.
murphy bed plans | build a murphy bed

Yeah, It's new for me actually i have no connection with development filed. But this HorizontalSlider based on ProgressBar is looking simple sweet and very attractive. I Thinks it is great way to progress. Thanks for sharing. Indian Handicrafts

I’ve truly enjoyed reading your blog posts. You obviously know your stuff. I also really like it that your website is very simple to navigate. I have bookmarked it in my favorites and will for sure be back for more.
assam how to attract a girl customer care number

It makes sense for a vertical slider of course, but not for a horizontal slider. Not the best example but try to load this page on an iPhone (or probably Android based device as well) and zoom into the horizontal slider.tinnitus miracle thomas coleman

In our onCreate () function we request that the title progress bar feature is enabled with the requestWindowFeature () method. Property Investment Then all we have to do is create a On Progress Change Listener for the slider and update the progress bar from there!

I found a lots of attractive things here particularly this discussion. Can you give some more information with details?
miracle mineral solution, tinnitus miracle and driver robot

Great post, been looking for android developer page for a while and stumbled on this one. Keep up the good work.

Freeman :Proactol Review

Hi. Useful information, many thanks to the author. It is puzzling to me now, but in general, the usefulness and importance is overwhelming. Very much thanks again and good luck! Please keep up the good articles, thanks! DUI Attorney

This is the first time I frequented your web page and thus far? I amazed with the research you made to create this particular publish incredible. Excellent job!

text spy

I am somewhat in agreement. There are some bits that are right and some that are wrong, but that my opinion, anyway it is still great stuff so I guess no real complaints from me.California DUI Lawyer

I am visiting this blog for first time. I am proud to say that I’ve become a great fan of this blog officially. A good blog always comes-up with new and exciting information like this one. Anyone who really wants to read a article with full of information, should read this.
Best Facial Moisturizer For Dry Skin

I also found your posts very interesting. In fact after reading, I had to go show it to my friend and he ejoyed it as well.Home Automation

Love to be like the bird and animals.parduotuve

Great information you've provided us with here. Thanks so much for sharing. Nice site too.FHA Loans

This is a fantastic website and I can not recommend you guys enough. Full of useful resource and great layout very easy on the eyes. Please do keep up this great work. Medical Assistant

Good tips ....

hopefully in the near future I can buy hp android ...
aamiin:)

regards
install ubuntu

Excellent post. It is very interesting and informative. Thanks. illy

there are several tutorials here. another useful stuff in helloandroid.

miracle mineral supplement | tinnitus miracle thomas coleman | driver robot review