Android Development Wheel control using the detailed

Source: Internet
Author: User

Out of the door not to be sick ah, casually two boxes of medicine more than 60 yuan. Okay, no nonsense, today we look at the use of wheel control, which is an open source control on GitHub, it is very convenient to use, we can use it to do a lot of things, such as a custom DatePicker, in some e-commerce app, often use it to do provincial and county level three linkage, In short, the use is quite a lot of, we will come together today to see how to use this stuff.

Let's take a look at one of today's things to do:


This is what we are going to do today. Let's get started.

1. Get Wheel

Wheel is an open source control on GitHub that we can download directly on GitHub, address Https://github.com/maarek/android-wheel, After the download, we can use the wheel file directly as a library, or we can copy the Java class and XML files inside the wheel into our project.

2. How to use

First, let's take a look at the main layout file:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" match_parent "> <Text         View android:id= "@+id/title" android:layout_width= "wrap_content" android:layout_height= "Wrap_content"        android:gravity= "center" android:text= "please select City"/> <linearlayout android:id= "@+id/content" Android:layout_width= "Fill_parent" android:layout_height= "wrap_content" android:layout_below= "@id/title "Android:background=" @drawable/layout_bg "android:orientation=" Horizontal "> <kankan.wheel.wid Get. Wheelview android:id= "@+id/province_view" android:layout_width= "0DP" Android:layout_heigh t= "Wrap_content" android:layout_weight= "1" > </kankan.wheel.widget.WheelView> <kankan . Wheel.widget.WheelView AndroiD:id= "@+id/city_view" android:layout_width= "0DP" android:layout_height= "Wrap_content" and            roid:layout_weight= "1" > </kankan.wheel.widget.WheelView> <kankan.wheel.widget.wheelview            Android:id= "@+id/area_view" android:layout_width= "0DP" android:layout_height= "Wrap_content"         android:layout_weight= "1" > </kankan.wheel.widget.WheelView> </LinearLayout> <button        Android:id= "@+id/confirm" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:layout_below= "@id/content" android:onclick= "OnClick" android:text= "OK"/></relativelayou T>

Well, in the main layout file we used three Wheelview, respectively, to represent the provinces and cities, in Mainactivity, we first have to get these three controls:

Provinceview = (Wheelview) This.findviewbyid (r.id.province_view); CityView = (Wheelview) This.findviewbyid (R.id.city_ view); Areaview = (Wheelview) This.findviewbyid (R.id.area_view);

After getting it, we want to use the Arraywheeladapter data adapter for data adaptation, here need two parameters, one is the context, the other is an array, this array is what we want to show, that is, we want to save the provinces, cities and counties are in the form of an array, But considering that a province corresponds to several municipalities, a city corresponds to several counties and counties, in order to link the provinces and cities together, we also use a map collection, so we design the data structure is this:

/** * Province */private string[] provincearray;/** * province-City */private map<string, string[]> citiesmap;/** * City-counties */private Ma P<string, string[]> Areasmap;

The first array saves all the data in the province, the second map saves the data for all the provinces, and the third map has the data for all the counties in the city, and now we're going to give this three data set assignment, let's take a look at our JSON data format:

[{"Name": "Beijing", "City": [{"Name": "Beijing", "area": ["Dongcheng", "Xicheng", "Chongwen District", "Xuanwu District" ...]} .....]

Our JSON data is such a format, the JSON data exists in the Assets folder, below we see how to parse the JSON data and assign value to the above three datasets:

private void Initjson () {citiesmap = new hashmap<string, string[]> (); areasmap = new hashmap<string, string[]> (); InputStream is = null;try {stringbuffer sb = new StringBuffer (), is = Getassets (). Open ("City.json"); int len = -1;byte[] BUF = new Byte[1024];while (len = Is.read (BUF))! =-1) {Sb.append (new String (buf, 0, Len, "GBK"));} Jsonarray ja = new Jsonarray (sb.tostring ());p Rovincearray = new String[ja.length ()]; string[] Citiesarr = null;for (int i = 0; i < provincearray.length; i++) {Jsonobject jsonprovince = ja.getjsonobject (i) ;p Rovincearray[i] = jsonprovince.getstring ("name"); Jsonarray jsoncities = Jsonprovince.getjsonarray ("city"); Citiesarr = new String[jsoncities.length ()];for (int j = 0; J &lt ; Citiesarr.length; J + +) {Jsonobject jsoncity = Jsoncities.getjsonobject (j); Citiesarr[j] = jsoncity.getstring ("name"); Jsonarray Jsonareas = Jsoncity.getjsonarray ("area"); string[] Areaarr = new String[jsonareas.length ()];for (int k = 0; k < jsonareas.length (); k++) {areaarr[k] = jsonareas.getstring (k);} Areasmap.put (Citiesarr[j], areaarr);} Citiesmap.put (Provincearray[i], Citiesarr);}} catch (IOException e) {e.printstacktrace ()} catch (Jsonexception e) {e.printstacktrace ();} finally {if (is = null) {try {Is.close ();} catch (IOException e) {e.printstacktrace ();}}}}
JSON parsing technology is not difficult, the logic here is a little bit more complex, using the three nested for loop, it is not difficult for everyone to ponder. Well, when there's data in the dataset, we can set the adapter for three wheel:

private void Initview () {Provinceview.setviewadapter (new arraywheeladapter<string> (Mainactivity.this, Provincearray);//default shows the city inside Beijing (only Beijing) Cityview.setviewadapter (New arraywheeladapter<string> ( Mainactivity.this, Citiesmap.get ("Beijing"));//Displays the county Areaview.setviewadapter (new arraywheeladapter<string) in Beijing by default > (Mainactivity.this, Areasmap.get ("Beijing"));//Display the first item provinceview.setcurrentitem (0) by default;// The first item Cityview.setcurrentitem (0) is displayed by default,//The first item Areaview.setcurrentitem (0) is displayed by default;//Page 7 is displayed Provinceview.setvisibleitems (7) ; Cityview.setvisibleitems (7); Areaview.setvisibleitems (7);//Add sliding event Provinceview.addchanginglistener (this); Cityview.addchanginglistener (this);}
After setting up the adapter we also set some default values, are very simple, you can directly see the comments, we set up here two listening events, we look at:

@Overridepublic void onChanged (Wheelview wheel, int oldValue, int newvalue) {if (wheel = = Provinceview) {//Update not only the city but also Also to update District updatecity (); Updatearea ();} else if (wheel = = CityView) {//update the city only with the update counties can be Updatearea ();}} private void Updatearea () {//Gets the subscript int cityindex = Cityview.getcurrentitem () of the currently displayed city,//Gets the subscript of the currently displayed province int provinceindex = P Rovinceview.getcurrentitem ();//Gets the name of the currently displayed province string provicename = provincearray[provinceindex];//Gets the name of the currently displayed city string Currentname = Citiesmap.get (provicename) [cityindex];//obtains all counties under the city under the name of the currently displayed city string[] areas = Areasmap.get ( Currentname);//Set the newly acquired data to Areaviewareaview.setviewadapter (new arraywheeladapter<string> (Mainactivity.this, Areas));//default display of the first item areaview.setcurrentitem (0);} private void Updatecity () {//obtains the currently displayed province's subscript int currentindex = Provinceview.getcurrentitem ();//Gets the name of the currently displayed province string Currentname = provincearray[currentindex];//obtains all municipalities in the province string[] cities = citiesmap.get (Currentname) According to the name of the province currently displayed;// Set the newly acquired data to Cityviewcityview.setviewadapter (new ArraywheelAdapter<string> (Mainactivity.this, cities));//Displays the first item Cityview.setcurrentitem (0) by default;} 

Almost every line of code has comments, and I'm not going to nag, and finally we'll look at the Click event:

public void OnClick (View v) {//obtains the currently displayed province's subscript int provinceindex = Provinceview.getcurrentitem ();//Gets the name of the currently displayed province string Provincename = provincearray[provinceindex];//Obtains the currently displayed city's subscript int cityindex = Cityview.getcurrentitem ();// Gets the name of the currently displayed city string cityname = Citiesmap.get (provincename) [cityindex];//gets the subscript int Areaindex of the currently displayed counties Areaview.getcurrentitem (); Toast.maketext (This, "The region you selected is" + Provincearray[provinceindex] + cityname+ areasmap.get (cityname) [Areaindex], Toast.length_short). Show ();}

OK, here we want the function basically implemented, but we can see that the system default style is slightly ugly, then I we can modify the source to get the style we want, first up and down the black side to see here:

Private int[] shadows_colors = new int[] {0xff111111, 0x00aaaaaa,0x00aaaaaa};
In the Wheelview.java file, this line of code defines the upper and lower black edge of the color changes, three parameters are the starting color, the transition color and the end of the color, then we can modify the source here to remove the black edge, and the middle of the transparent East black not to pull, we want to change, through the source found this file W Heel_val.xml:

<shape xmlns:android= "Http://schemas.android.com/apk/res/android" ><gradientandroid:startcolor= "# 70222222 "android:centercolor=" #70222222 "android:endcolor=" #70EEEEEE "android:angle="/><stroke android: Width= "1DP" android:color= "#70333333"/> </shape>
This defines the style of the middle transparent bar, which we can modify according to our own needs. Well, the source code here is not too much, it is not difficult, we can go to ponder over their own, about the introduction of wheel we say so much.


This article demo download https://github.com/lenve/wheelTest


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced. If there is a wrong place, I would appreciate it if I could criticize it.

Android Development Wheel control using the detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.