domingo, 1 de abril de 2012

How to use Android Wheel Part II


UPDATE 2016: This guide has a new version that is Android Studio / Gradle / Github friendly! Click here for the article.

The first thing we have to do is define how many columns we will need for the wheel and write an Adapter for each one. These adapters will help us to fill with data every column.

To make the things easier, the following Adapters are ready to use:

NumericWheelAdapter. As is name indicates, this adapter is useful when we just want to fill a column with a sequence of numbers. To use it is necessary to pass in the constructor the first and last number of the sequence.

ArrayWheelAdapter. With this adapter we can fill the column with a defined array and indicate the current value. The array must be String type.

AbstractWheelTextAdapter. This adapter is more flexible than the two previous. In order to use it, we have to create our own adapter and inherit from this class. I will use this adapter for the example so I will explain it in detail later on.

AbstractWheel Adapter. This is the most flexible of all adapters; we can use to fill the columns with any kind of object, for example, images.

In this example we are going to make a picker date so we will need four columns: one for the days, one for the hours, other for the minutes, and one more for the am, pm marker.


For the first column we’ll create one class (which I’ve named “DayWheelAdapter.java”) that inherits from AbstractWheelTextAdapter, but first is necessary define an XML to customize the text of the columns. This XML will work for the four columns.

wheel_item_time.xml
<?xml version="1.0" encoding="utf-8"?>
 <TextView xmlns:android="http://schemas.android.com/apk/res/android"
             android:id="@+id/time_item"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:textSize="20dp"
             android:lines="1"
             android:textStyle="bold"
             android:textColor="#FF111111"
             android:layout_gravity="right" />

Now that we have the XML that will contain the text of the column we can create the DayWheelAdapter class. Let’s see the code below:

DayWheelAdapter.java
public class DayWheelAdapter extends AbstractWheelTextAdapter {

       ArrayList<Date> dates;

       //An object of this class must be initialized with an array of Date type
       protected DayWheelAdapter(Context context, ArrayList<Date> dates) {
       //Pass the context and the custom layout for the text to the super method
             super(context, R.layout.wheel_item_time);
             this.dates = dates;
       }

       @Override
    public View getItem(int index, View cachedView, ViewGroup parent) {
             View view = super.getItem(index, cachedView, parent);
             TextView weekday = (TextView) view.findViewById(R.id.time_item);

             //Format the date (Name of the day / number of the day)
             SimpleDateFormat dateFormat = new SimpleDateFormat("EEE dd");
             //Assign the text
             weekday.setText(dateFormat.format(dates.get(index)));
            
             if (index == 0) {
                    //If it is the first date of the array, set the color blue
                    weekday.setText("Today");
                    weekday.setTextColor(0xFF0000F0);
        }
             else{
                    //If not set the color to black
                    weekday.setTextColor(0xFF111111);
             }
            
             return view;
       }
      
       @Override
       public int getItemsCount() {
             return dates.size();
       }

       @Override
       protected CharSequence getItemText(int index) {
             return "";
       }

}


For the second and third columns (hours and minutes respectively) we’ll use the NumericWheelAdapter and for the am pm marker column we’ll apply the ArrayWheelAdpter. In the last piece of code we’ll see how to use them, before, let’s create the XML that actually contains the Android Wheel.

In the dialog_date.xml file I’ve used one “Kankan.wheel.widget.WheelView” label for each column; this widget is the one that simulates the fancy wheel.

dialog_date.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="5dp" >

    <LinearLayout android:id="@+id/wheel"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_gravity="center_horizontal"
        android:paddingBottom="30dp">
     
        <kankan.wheel.widget.WheelView android:id="@+id/day"
            android:layout_height="wrap_content"
            android:layout_width="100dp"/>
        <kankan.wheel.widget.WheelView android:id="@+id/hour"
            android:layout_height="wrap_content"
            android:layout_width="40dp"/>
        <kankan.wheel.widget.WheelView android:id="@+id/minute"
            android:layout_height="wrap_content"
            android:layout_width="40dp"/>
        <kankan.wheel.widget.WheelView android:id="@+id/ampm"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"/>           
    </LinearLayout>

    <Button android:id="@+id/set"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/wheel"
        android:text="@string/setButton"/>
    <Button android:id="@+id/cancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/wheel"
        android:layout_toRightOf="@id/set"
        android:text="@string/cancelButton"/> 
               
</RelativeLayout>

Finally in the following piece of code, I show how to configure each column using the “WheelView” class and an Adapter for each one.


//Array for the am/pm marker column
String[] ampmArray = new String[]{"am","pm"};

//With a custom method I get the next following 10 days from now
ArrayList<Date> days = DateUtils.getNextNumberOfDays(new Date(), 10);
            
//Create a custom dialog with the dialog_date.xml file
Dialog dialogSearchByDate = new Dialog(this);
dialogSearchByDate.setContentView(R.layout.dialog_date);
dialogSearchByDate.setTitle("Date");

//Configure Days Column
WheelView day = (WheelView) dialogSearchByDate.findViewById(R.id.day);
day.setViewAdapter(new DayWheelAdapter(this,days));

//Configure Hours Column
WheelView hour = (WheelView) dialogSearchByDate.findViewById(R.id.hour);
NumericWheelAdapter hourAdapter = new NumericWheelAdapter(this, 1, 12);
hourAdapter.setItemResource(R.layout.wheel_item_time);
hourAdapter.setItemTextResource(R.id.time_item);
hour.setViewAdapter(hourAdapter);
       
//Configure Minutes Column
WheelView min = (WheelView) dialogSearchByDate.findViewById(R.id.minute);
NumericWheelAdapter minAdapter = new NumericWheelAdapter(this, 00, 59);
minAdapter.setItemResource(R.layout.wheel_item_time);
minAdapter.setItemTextResource(R.id.time_item);
min.setViewAdapter(minAdapter);
       
//Configure am/pm Marker Column
WheelView ampm = (WheelView) dialogSearchByDate.findViewById(R.id.ampm);
ArrayWheelAdapter<String> ampmAdapter = new ArrayWheelAdapter<String>(this, ampmArray);
ampmAdapter.setItemResource(R.layout.wheel_item_time);
ampmAdapter.setItemTextResource(R.id.time_item);
ampm.setViewAdapter(ampmAdapter);
       
dialogSearchByDate.show();



Well that’s it, this is how I implemented Android Wheel. 

Over time I realized that (or at least that's what I think) is better to keep the look and feel for every platform and not try to mix them in order to give consistence to the user, but that’s up to you.

44 comentarios:

  1. Hi, where did you define the getNextNumberOfDays() method? Thanx for the implementation

    ResponderEliminar
  2. Hi Gerhardt, thanks for reading. I have a helper class called DateUtils where I implemented some static methods to handle dates, here's the implementation of getNextNumberOfDays() hope it helps.

    public static ArrayList getNextNumberOfDays(Date originalDate,int days){
    ArrayList dates = new ArrayList();
    long offset;
    for(int i= 0; i<= days; i++){
    offset = 86400 * 1000L * i;
    Date date = new Date( originalDate.getTime()+offset);
    dates.add(date);
    }
    return dates;
    }

    ResponderEliminar
  3. i want full code with package
    send me please
    mayanklangalia@gmail.com

    ResponderEliminar
  4. I love you man! This tutorial was most helpful :-)

    ResponderEliminar
    Respuestas
    1. if you have sample code then please share
      need your help for creating this tutorial
      mayanklangalia@gmail.com

      Eliminar
  5. hi its very helpful
    can u send me the full source code to my mail id karthikbabludeep@gmail.com
    thanks in advance!!!

    ResponderEliminar
  6. Can U send me the full code for this project..It is really good.. rkosharil@gmail.com

    ResponderEliminar
  7. It's really good tutorial but can u send me full code for example please ?
    Marko.obradovich@gmail.com

    ResponderEliminar
  8. Nelida, It is nice tutorial. Can I use this in Android Studio? And please send this source to me mehmet4cakmak@gmail.com
    Best Wishes from sunny and beautiful Istanbul, Turkey

    ResponderEliminar
  9. hi it's very helpful please send me the code in my id
    kkprajapati1990@gmail.com

    ResponderEliminar
  10. hi
    You have a superb work.Will you please send the full code to my email id: rajivnanda100@gmail.com
    I think it will help me to develop a good app. So please send the full code.

    ResponderEliminar
  11. When I use kankan wheel demo project, in DateActivity, there is a problem:
    When day value "31" it is not updating days field.

    ResponderEliminar
  12. I have an sample app that has four spinning wheels with date, hour, minute and am(or pm). and i got d values (hour, minutes & am(or pm)) but i have one problem of getting days value because in my case did not get proper position so, please
    can anyone tell me, How can i get proper values from these wheels ? please see my below code.

    private class DayArrayAdapter extends AbstractWheelTextAdapter {
    private final int daysCount = 365;
    @SuppressWarnings("unused")
    int index_item = 0;
    int day = 0;
    Calendar calendar;

    protected DayArrayAdapter(Context context, Calendar calendar) {
    super(context, R.layout.day, NO_RESOURCE);
    this.calendar = calendar;
    setItemTextResource(R.id.monthday);
    data = new ArrayList();
    }

    public int getItemId(int arg0) {
    return arg0;
    }

    public View getItem(int index, View cachedView, ViewGroup parent) {
    //int day = -daysCount / 2 + index;
    this.index_item = index;
    day = index;
    Calendar newCalendar = (Calendar) calendar.clone();
    newCalendar.roll(Calendar.DAY_OF_YEAR, day);
    View view = super.getItem(index, cachedView, parent);
    weekday = (TextView) view.findViewById(R.id.weekday);
    if (day == 0) {
    weekday.setText("");
    } else {
    DateFormat format = new SimpleDateFormat("EEE");
    weekday.setText(format.format(newCalendar.getTime()));
    }

    monthday = (TextView) view.findViewById(R.id.monthday);
    if (day == 0) {
    monthday.setText("Today");
    monthday.setTextColor(0xFF0000F0);

    } else {
    DateFormat format = new SimpleDateFormat("MMM d");
    monthday.setText(format.format(newCalendar.getTime()));
    monthday.setTextColor(0xFF111111);

    data.add(format.format(newCalendar.getTime()));

    }
    return view;
    }

    public ArrayList getText() {
    return data;
    }

    public int getItemsCount() {
    return daysCount + 1;
    }

    protected CharSequence getItemText(int index) {
    return "";
    }
    }

    ResponderEliminar
    Respuestas
    1. Hi Mayank,
      you got the source code. if you got please share me sample code at
      vishal.patil1988@gmail.com

      Eliminar
  13. Please send me full source code for that
    vishal.patil1988@gmail.com

    ResponderEliminar
    Respuestas
    1. Take a look at the updated article, it includes a Github project with the full source code, and new instructions to integrate everything through Android Studio and gradle.

      http://tolkianaa.blogspot.com/2016/01/how-to-use-android-wheel-v2-android.html

      Eliminar
  14. Just stumbled across your blog and was instantly amazed with all the useful information that is on it. Great post, just what i was looking for and i am looking forward to reading your other posts soon!
    python training in pune
    python online training
    python training in OMR

    ResponderEliminar
  15. I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post.is article.
    python training in pune
    python online training
    python training in OMR

    ResponderEliminar
  16. Thanks for the informative article. This is one of the best resources I have found in quite some time. Nicely written and great info. I really cannot thank you enough for sharing.
    Blueprism training institute in Chennai

    Blueprism online training

    Blue Prism Training Course in Pune

    Blue Prism Training Institute in Bangalore

    ResponderEliminar
  17. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information..
    angularjs-Training in tambaram

    angularjs-Training in sholinganallur

    angularjs-Training in velachery

    angularjs Training in bangalore

    angularjs Training in bangalore

    ResponderEliminar
  18. Interesting Post. Looking for this information for a while. Thanks for Posting.

    Article submission sites
    Education

    ResponderEliminar
  19. Nice blog..! I really loved reading through this article. Thanks for sharing such a amazing post with us and keep blogging...Well written article pmp training in chennai | pmp training institute in chennai | pmp training centers in chennai| pmp training in velachery | pmp training near me | pmp training courses online

    ResponderEliminar
  20. Thank you for sharing such great information with us. I really appreciate everything that you’ve done here and am glad to know that you really care about the world that we live in

    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training

    ResponderEliminar
  21. Very good information. Its very useful for me. We need learn from real time examples and for this we choose good training institute, we need to learn from experts . So we make use of demo classes . Recently we tried linux demo class of Apponix Technologies.


    ResponderEliminar
  22. I am very happy to visit your blog. This is definitely helpful to me, eagerly waiting for more updates.web design company in velachery

    ResponderEliminar