Android learning Demo (21) linked selection of ListView, androidlistview

Source: Internet
Author: User
Tags getcolor

Android learning Demo (21) linked selection of ListView, androidlistview

In daily App development, especially in the development and life service applications, we often need to display data in provinces, cities, and cities in a coordinated manner. The requirements are as follows:

1) show all provinces

2) When you click a province, the list of cities under the province is displayed on the level-2 menu.

3) Select and return to display the selected City

4) when you re-enter the selection page, the value of the last selected (or currently selected) is identified.

Is a similar ListView linkage Selection control.

1) first define a Layout, and place a ListView between the left and right. The approximate interface is as follows:


2) define a custom control (ValuePicker). In the control, first we need to obtain the data filled with two ListView. If it is a province or city, we need to obtain the data of the province or city, in this Demo, we use the DataProvider class to simulate some data, as shown below:

public class DataProvider {public static final String[] summaries = {"A","B","C","D","E","F","G","H"};public 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"});}}

Then reference the data in ValuePicker.

private String[] summaries = DataProvider.summaries;private Map<String, String[]> details = DataProvider.details;

3) To bind data to the corresponding ListView, we must declare an Adapter for the two ListView respectively. Here, we inherit the BaseAdapter and create a SingleCheckedListAdpater.

Because the ListView provided by Android itself has no selected effect, and based on our needs,

3.1) When you click an Item, you need to set the selected status of the Item. Here, we use "Black and White" to reverse the color to highlight the effect.

3.2) When we click another Item, we need to reset the original Item to the unselected state, that is, to reset its background and font color, change to "White-black", and set the Item in the current selection to selected.

3.3) a special case is that if the number in the ListView exceeds the current screen, when we slide the ListView, The ListView will reuse the previously created View, we must make a special process for the selected Item. If the selected Item slides out of the screen, its corresponding View will be reused. Therefore, it must be set to unselected when it is reused, when it slides back into the screen, it is set to the selected status.

Based on the above situations, we need to record the position and View of a selected Item in the Adapter. The Code is as follows:

/** * the View checked */private TextView mLastCheckedView = null;/** * the position in the data */private int mCheckedPosition = -1;public void setCheckedPosition(int position){mCheckedPosition = position;}.../** * @param checkedView the checkedView to set */public void setCheckedView(View checkedView) {setViewSelected(mLastCheckedView, 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));}}}

During getView, the status of the View is processed based on the selected position, as shown below:

@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 needs to refresh the data, so the Adapter must also provide the corresponding entry to refresh the data.

public void setData(String[] data){mData = data;mLastCheckedView = null;mCheckedPosition = -1;notifyDataSetChanged();}

4) Obviously, we must record the selected value in the ValuePicker control to find the corresponding position in the data source and pass it to the Adapter. Therefore, we define two locations 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 specific applications, these variables can be customized based on specific business information.

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 is bound to the Adapter, we need to pass this value over. Here, we don't need to care about its value, because it will be processed in the 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);
Note that when the left value is selected, we need to find the corresponding content of the ListView on the right, and bind it to the ListView on the right.

In OnItemClickListener, We need to reset this value based on the selected 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 an OnClickListener, which aims to pass the operation event of this button to the caller, because after selection, the subsequent processing logic should be handled by the caller.

/** * Listener to handle the logic when current city card number is selected */public OnClickListener mListener;/** * @param listener the listener to set */public void setButtonOnClickListener(OnClickListener listener) {this.mListener = listener;}...btnConfirm.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {if(mListener != null){mListener.onClick(arg0);}}});

5) After all the preceding operations are completed, the Custom interaction ListView Selection control is complete. You can use it in layout, as shown below:

    <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 as follows:

Public class extends Activity implements OnClickListener {public static final String SELECTED_LEFT = "SELECTED_LEFT"; public static final String SELECTED_RIGHT = "SELECTED_RIGHT"; private ValuePicker vpTest; @ Overrideprotected void onCreate (Bundle release) {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, "select the value on the right", Toast. LENGTH_SHORT ). show (); return;} Intent data = new Intent (); data. putExtra (SELECTED_LEFT, vpTest. getLeftVaue (); data. putExtra (SELECTED_RIGHT, vpTest. getRightValue (); setResult (RESULT_ OK, data); finish ();}}

End! Download the source code.


How to Use ListView to complete a small android instance

Customize an Adapter and overwrite getView.

I learned about Android and wrote a small demo of the View class, but I don't understand it.

This is the original statement in the API:

SetMinimumWidth

Public void setMinimumWidth (int minWidth)
Sets the minimum width of the view. It is not guaranteed the view will be able to achieve this minimum width (for example, if its parent layout constrains it with less available width ).

Parameter: minWidth-The minimum width the view will try to be.
Meaning:
Set the minimum width of the view. It is the minimum width that a view cannot guarantee to achieve this goal (for example, if its parent layout limits its available width ). The meaning of another method is similar.

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.