Android Learning Mini Demo (+) ListView linkage Selection

Source: Internet
Author: User

In the daily application development, especially in the development of life services applications, many times, we will need to display the data of the provincial urban areas, such as the demand is as follows:

1) Show all Provinces

2) when clicking on a province, show the list of cities to which this province belongs under the two-level menu

3) Check back to show the cities we selected

4) When you re-enter the selection page, identify the value of our last selection (or currently selected by the people)

is a similar ListView linkage selection control.

1) First define a layout, left and right each place a ListView, the approximate interface is as follows:


2) Customizing a Control (Valuepicker), in the control, first we want to get the data filled with two ListView, if it is the provinces and cities, it is necessary to obtain the data of the provinces and cities, in this demo, we use Dataprovider this class, to simulate some of the data, as follows:

public class Dataprovider {public static final string[] summaries = {"A", "B", "C", "D", "E", "F", "G", "H"};p ublic static final map<string, string[]> details = new hashmap<> (); static {Details.put ("A", new string[] {"A1", "A2", "A3"}), Details.put ("B", new string[] {"B1", "B2", "B3"}), Details.put (" C ", new string[] {" C1 "," C2 "," C3 "}); Details.put ("D", new string[] {"D1", "D2", "D3"}); Details.put ("E", new string[] {"E1", "E2", "E3"}); Details.put ("F", new string[] {"F1", "F2", "F3"}); Details.put ("G", new string[] {"G1", "G2", "G3"}); Details.put ("H", new string[] {"G1", "H2", "H3"});}}

The data is then referenced in the Valuepicker.

Private string[] summaries = dataprovider.summaries;private map<string, string[]> details = dataprovider.details;

3) to bind the data to the corresponding ListView, we must declare a adapter for each of the two ListView, where we inherit Baseadapter and create a singlecheckedlistadpater.

Since the ListView provided by Android itself is not a checked effect, and based on our needs,

3.1) When the user clicks on item, set the item selected state, here, we are using "white on black", invert the color to highlight the effect.

3.2) and when we click on another item, we need to reset the original item to an unchecked state, that is, to reset its background and font color, turn it back to "black on white", and set the currently selected item to selected.

3.3) A special case is that the number inside the ListView is outside the current screen, and when we swipe the ListView, the ListView will reuse the view we've created before, so we have to do a special deal with the selected item. The selected item, if it slides out of the screen, its corresponding view is reused, so it must be placed unchecked when it is reused, and when it slides back into the screen, it is selected.

Based on the above cases, we need to record the location and view of a selected item in adapter, with the following code:

/** * The View checked */private TextView mlastcheckedview = null;/** * The position in the data */private int Mcheckedpos ition = -1;public void setcheckedposition (int position) {mcheckedposition = position;} .../** * @param checkedview the Checkedview to set */public void Setcheckedview (View checkedview) {setviewselected (mlastch Eckedview, false); TextView TextView = (TextView) checkedview;setviewselected (TextView, True);} private void setviewselected (TextView view, Boolean selected) {if (view! = null) {if (selected) {View.setbackgroundcolor ( Mcontext.getresources (). GetColor (R.color.black)); View.settextcolor (Mcontext.getresources (). GetColor ( R.color.white)); mlastcheckedview = view;} Else{view.setbackgroundcolor (Mcontext.getresources (). GetColor (R.color.white)); View.settextcolor ( Mcontext.getresources (). GetColor (R.color.black));}}

In GetView, the status of the view is handled according to the selected location, as follows:

@Overridepublic view GetView (int position, view convertview, ViewGroup root) {Viewholder holder = null;if (Convertview = = NULL) {holder = new Viewholder (); Convertview = Layoutinflater.from (Mcontext). Inflate (R.layout.list_item_card_number, NULL); holder.name = (TextView) Convertview.findviewbyid (r.id.textview1); Convertview.settag (holder);} Else{holder = (Viewholder) Convertview.gettag ();} Setviewselected (holder.name, mcheckedposition = = position); Holder.name.setText (Mdata[position]); return Convertview ;}

In addition, because it is a linked ListView, when an item on the left is clicked, the ListView on the right will refresh the data, so adapter must also provide the corresponding entry to refresh the data.

public void SetData (string[] data) {Mdata = Data;mlastcheckedview = Null;mcheckedposition = -1;notifydatasetchanged ();}

4) and obviously, we must also record the selected value in the Valuepicker control in order to find its corresponding position in the data source and pass it to adapter. Therefore, we will define two positions and corresponding values in Valuepicker.

private int mposleft = -1;private string mcurleft;private int mposright = -1;private string mcurright;

This is just a simple definition in this demo, in the specific application, these variables can be based on specific business information to customize the variable name.

The following code finds the corresponding location.

for (int i = 0; i < len; i++) {String summary = summaries[i];if (Summary.equals (mcurleft)) {mposleft = I;break;}} if (mposleft >= 0) {String summary = Summaries[mposleft];  String[] right = Details.get (summary); int lenofright = right.length;for (int j = 0; J < Lenofright; J + +) {String detail = Right[j];if (mcurright! = null && detail.equals (mcurright)) {mposright = J;break;}}}

Then, when the ListView binds to the adapter, we need to pass this value over, where we don't have to care about its value, because it's handled in adapter.

Final Singlecheckedlistadapter ladapter = new Singlecheckedlistadapter (mcontext, summaries); Ladapter.setcheckedposition (Mposleft); Lvleft.setadapter (Ladapter); String[] rights = new String[]{};if (mposleft >= 0 && mposright >= 0) {rights = Details.get (summaries[mposleft ]);} Final Singlecheckedlistadapter radapter = new Singlecheckedlistadapter (mcontext, rights); radapter.setcheckedposition (mposright); Lvright.setadapter (Radapter);
It is also important to note that when the left value is selected, we have to find the contents of the corresponding ListView on the right, and bind it to the right listview.

In Onitemclicklistener, we have to reset this value according to our chosen position.

Lvleft.setonitemclicklistener (New Onitemclicklistener () {@Overridepublic void Onitemclick (adapterview<?> arg0 , view view, int position, long id) {mcurright = null;ladapter.setcheckedposition (position); Ladapter.setcheckedview ( view); mposleft = Position;radapter.setdata (Details.get (Summaries[mposleft));}); Lvright.setonitemclicklistener (New Onitemclicklistener () {@Overridepublic void Onitemclick (adapterview<?> arg0, view view, int position, long id) {radapter.setcheckedposition (position); Radapter.setcheckedview (view); Mcurright = Details.get (Summaries[mposleft]) [position];}});

Finally, in Valuepicker, we also define a onclicklistener, which is intended to pass the action event of the button to the caller, because the subsequent processing logic should be handled by the caller when the selection is finished.

/** * Listener to handle, the logic when current City card number is selected */public onclicklistener mlistener;/** * @par AM listener the listener to set */public void Setbuttononclicklistener (Onclicklistener listener) {This.mlistener = Listene R;} ... btnconfirm.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View arg0) {if (Mlistener! = null) {Mlistener.onclick (arg0);}});

5) When all of the above has been implemented, this custom linkage ListView selection control is completed and can be used in layout, as follows:

    <com.lms.twofoldselector.valuepicker        android:id= "@+id/vptest"        android:layout_width= "Match_parent"        android:layout_height= "Match_parent" >    </com.lms.twofoldselector.ValuePicker>

Initialize it in the activity as follows:

public class Valuepickermockactivity extends Activity implements onclicklistener{public static final String selected_ left = "Selected_left";p ublic static final String selected_right = "Selected_right";p rivate valuepicker vptest;@ overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_vp_mock); vptest = (Valuepicker) Findviewbyid (r.id.vptest); Vptest.setbuttononclicklistener (This) ;//set the selected Viewintent intent = getintent (); String Leftvalue = Intent.getstringextra (selected_left); String Rightvalue = Intent.getstringextra (selected_right); Vptest.setleftvalue (Leftvalue); Vptest.setrightvalue ( Rightvalue); Vptest.initialize ();} @Overridepublic void OnClick (View arg0) {String rightvalue = Vptest.getrightvalue (); if (rightvalue = = null) { Toast.maketext (This, "Please select the right value", Toast.length_short). Show (); return;} Intent data = new Intent ();d Ata.putextra (Selected_left, Vptest.getleftvaue ());d Ata.putextra (Selected_right, Vptest.getrightvAlue ()); Setresult (RESULT_OK, data); Finish ();}} 

End!source code download.

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.