Android component-based development (2)-RadioButton matrix for grid layout

Source: Internet
Author: User
Tags addall

Android component-based development (2)-RadioButton matrix for grid layout

**

Preface

**
In Android, we usually use RadioGroup to manage a set of RadioButton to achieve the mutex effect of single-choice buttons. However, in some requirements, the RadioButton matrix composed of N rows and N columns needs to be completed. However, our RadioGroup is a straight LinearLayout and cannot complete the grid layout (transformation Transformation). So next I will introduce the idea of RadioButton for grid layout.
No picture, no truth. First click ~

** <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4NCjxoMiBpZD0 = "Train of Thought"> ideas

**
When it comes to grid layout, the simplest thing is to use the system's GridView for implementation. What we need to do is to add RadioButton to the GridView and then implement the mutual exclusion between RadioButton.
1. Custom RadioButton:
Customize a RadioButton named IconRadioButton.

/*** Created by jk on 2016/1/20. * Custom RadioButton */public class extends LinearLayout {private Context mContext; private Resources mResources; private boolean mIsCheck; private View mContentView; private ImageView mRadio; private TextView mTextView; private ColorStateList mTextColor; public IconRadioButton (Context context) {this (context, null);} public IconRadioButton (Context c Ontext, AttributeSet attrs) {this (context, attrs, 0);} public IconRadioButton (Context context, AttributeSet attrs, int defStyleAttr) {super (context, attrs, defStyleAttr ); init (context);} private void init (Context context) {mContext = context; mResources = context. getResources (); mContentView = LayoutInflater. from (context ). inflate (R. layout. btn_icon_radio, this); mRadio = (ImageView) mContentVi Ew. findViewById (R. id. radio); mTextView = (TextView) mContentView. findViewById (R. id. text);} public void setChecked (boolean isChecked) {mIsCheck = isChecked; changeUIByChecked (isChecked);} public boolean isChecked () {return mIsCheck;} private void changeUIByChecked (boolean isChecked) {if (mRadio. getVisibility ()! = GONE) {mRadio. setImageResource (isChecked? R. drawable. radio_selected: R. drawable. radio_unselected);} mTextView. setEnabled (isChecked);} public void setTextColor (ColorStateList color) {mTextColor = color; mTextView. setTextColor (color);} public void setText (CharSequence text) {mTextView. setText (text);} public void setText (int resId) {mTextView. setText (resId);} public void hiddenRadio (boolean isHidden) {mRadio. setVisibility (isHidden? GONE: VISIBLE );}}

This IconRadioButton is simply a LinearLayout, which encapsulates the methods for changing the text and button styles based on whether or not they are selected.

Btn_icon_radio.xml

<code class=" hljs xml"><!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%2D%2D%3E--><linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="left" android:paddingbottom="5dp" android:paddingtop="5dp">    <imageview android:id="@+id/radio" android:layout_width="42dp" android:layout_height="match_parent" android:layout_gravity="center_vertical" android:gravity="center" android:src="@drawable/radio_selected" android:textcolor="#FF1CBFA6">    <textview android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="center_vertical" android:gravity="center" android:textcolor="#FF999999" android:textsize="14dp"></textview></imageview></linearlayout></code>

The layout file is simply a LinearLayout with an ImageView and a TextView.

2. Define a data model

/*** Created by admin on 2016/1/20. */public class RadioItemModel {public String text; // The RadioButton text public boolean isChecked; // whether to select public boolean hiddenRadio; // whether to hide radio public ColorStateList textColor; // color of the text in different States: public RadioItemModel (String text, boolean isChecked, boolean hiddenRadio, ColorStateList textColor) {this. text = text; this. isChecked = isChecked; this. hiddenRadio = hiddenRadio; this. textColor = textColor;} public RadioItemModel (String text) {this. isChecked = false; this. hiddenRadio = false; this. textColor = null; this. text = text;} public void setText (String text) {this. text = text;} public String getText () {return text;} public boolean isChecked () {return isChecked ;}}

We define a data model to store various RadioButton attributes. ColorStateList is used to control the color of TextView in different states, such as state_pressed.

3. Define the Adapter:
Since the GridView is used, we need to define our Adapter. Our mutex logic is also implemented in the Adapter.

/*** Created by jk on 2016/1/20. * function: adapter for the radio matrix * purpose: the RadioGroup of the system is a straight LinearLayout partition (linear partition) Partition. The layout of * N rows and N columns cannot be completed. So to implement grid layout of Single-choice buttons, re-define */public class GridRadioAdapter extends BaseAdapter {private List
  
   
MList; private Context mContext; private Resources mResources; private OnItemCheckedListener mListener; // callback function public interface OnItemCheckedListener {void onItemChecked (RadioItemModel model, int position) selected by RadioButton );} public void setOnItemCheckedListener (OnItemCheckedListener listener) {this. mListener = listener;} public GridRadioAdapter (Context context, List
   
    
List) {mContext = context; mList = list; check () ;}private void check () {if (mList. size ()> = 0 & mList! = Null) {checkdefacheckchecked (); checkMutex () ;}/ *** check the mutex event. By default, only one check event can be selected, select the last */private void checkMutex () {int checkCount = 0; for (RadioItemModel item: mList) {if (item. isChecked) {checkCount ++ ;}} if (checkCount >=2) {setOtherUnChecked (checkCount-1) ;}} private void setOtherUnChecked (int position) {for (int I = 0; I <mList. size (); I ++) {if (I! = Position) {RadioItemModel item = mList. get (I); item. isChecked = false;} else {mList. get (position ). isChecked = true ;}} public RadioItemModel getItemChecked () {for (int I = 0; I <mList. size (); I ++) {RadioItemModel item = mList. get (I); if (item. isChecked) return item;} return null;}/*** check whether there is a default selected button. If no default one is selected, */private void checkdefacheckchecked () {for (RadioItemModel item: mList) {If (item. isChecked) return;} mList. get (0). isChecked = true;} @ Override public int getCount () {return mList = null? 0: mList. size () ;}@ Override public Object getItem (int position) {if (mList! = Null & mList. size ()> position) return mList. get (position); return null ;}@ Override public long getItemId (int position) {return position ;}@ Override public View getView (final int position, View convertView, ViewGroup parent) {IconRadioButton iconBean = null; iconBean = new IconRadioButton (mContext); final RadioItemModel model = mList. get (position); if (! TextUtils. isEmpty (model. text) {iconBean. setText (model. text);} iconBean. setChecked (model. isChecked); if (model. textColor! = Null) {iconBean. setTextColor (model. textColor);} iconBean. hiddenRadio (model. hiddenRadio); final IconRadioButton finalIconBean = iconBean; iconBean. setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {if (! FinalIconBean. isChecked () {setOtherUnChecked (position); if (mListener! = Null) {mListener. onItemChecked (model, position) ;}yydatasetchanged () ;}}); return iconBean ;} public void addAll (List
    
     
List) {mList. clear (); if (list. size ()> = 0 & list! = Null) {mList. addAll (list); check (); yydatasetchanged ();}}}
    
   
  

In the constructor, we call the check method to implement the default check and mutex check.
(1) The checkdefacheckchecked function is used to implement the default selection function. If no button is selected by default for the data passed to us, we will make the first button selected by default.
(2) The checkMutex function is used to check mutex events. If multiple buttons are selected at the same time, we set the last selected button to the selected status, and the others to the unselected status. For example, if Buttons 1, 3, and 5 are selected at the same time, we set 5 to the selected status, and 1 and 3 are not selected.
(3) OnItemCheckedListener is the callback method when the button is selected.

4. Usage

The usage is very simple and rude ~

Public class MainActivity extends Activity {private GridView mGridLayout; private GridRadioAdapter mAdapter; private List
  
   
MItemList; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (events); setContentView (R. layout. activity_main);} private void initData () {mItemList = new ArrayList
   
    
(); ColorStateList csl = getResources (). getColorStateList (R. color. ddt_color_tab_text); mItemList. add (new RadioItemModel ("all", false, true, csl); mItemList. add (new RadioItemModel ("before breakfast", false, true, csl); mItemList. add (new RadioItemModel ("before lunch", false, true, csl); mItemList. add (new RadioItemModel ("before dinner", false, true, csl); mItemList. add (new RadioItemModel ("after breakfast", false, true, csl); mItemList. add (new RadioItemModel ("after lunch", false, true, csl); mItemList. add (new RadioItemModel ("after dinner", false, true, csl); mItemList. add (new RadioItemModel ("before going to bed", false, true, csl); mAdapter. notifyDataSetChanged ();}}
   
  

PS: If the hiddenRadio attribute is set to true, we can achieve the following effect. So this item can also be used to switch the Fragment tab ~~~ O (partition _ partition) O

Above.

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.