Android Learning Mini Demo (+) ListView linkage Selection

Source: Internet
Author: User
Tags getcolor

In the daily application development, especially in the development of life services applications, very often, we will need to display the data of the provincial urban areas, such as the need for example:

1) Show all Provinces

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

3) Check back to show the cities we selected

4) When you go to the selection page again, identify the value that we last checked (or currently selected)

is a similar ListView linkage selection control.

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


2) define a control (Valuepicker), in the control, first we want to fill two ListView data, assuming that the provinces and cities, we need to obtain the data of the provinces and cities, in this demo, we use the Dataprovider class, to simulate some data, For example, the following:

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 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 the 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 place the original item again in the unchecked state, that is, to set its background and font color again and again to "black on white", and to select the currently selected item.

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, assuming it slides out of the screen, its corresponding view will be reused, so it must be placed unchecked when it is reused, and when it slides into the screen again, it is selected.

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

/** * 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));}}

When GetView, the status of the view is handled based on whether it is selected, such as the following:

@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 accordingly, so adapter must also provide the appropriate 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 before we can 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 detailed application, these variables can be based on the detailed business information to define their own variable name.

The following code finds the appropriate 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 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 want to find out the contents of the corresponding ListView on the right, and bind it to the right listview.

In Onitemclicklistener, we are going to set this value again, based on 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 when the selection is finished, perhaps the processing logic should be handled by the caller.

/** * 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 achieved, this self-defined linkage ListView selection control is finished and can be used in layout, such as the following:

    <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 activity, such as the following:

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 download.

Android Learning Mini Demo (+) ListView linkage Selection

Related Article

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.