Android custom RadioGroup layout, androidradiogroup

Source: Internet
Author: User

Android custom RadioGroup layout, androidradiogroup

This effect was required in the project some time ago to customize the RadioGroup layout, but the premise is to find RadioButton. I collected various materials and tried various tests. Finally, the custom RadioGroup layout is available. CustomYiRadioGroup layout, which can contain various la S. RadioButton is also in this layout. The recursive search method can be used to find the RadioButton id or a group. Next, let's look at the code.

Reprinted with the source: click here

Welcome to download the test demo: click here

1. Customize the mmnestradiogroup class.

Package com. example. customgroupdemo; import android. annotation. targetApi; import android. content. context; import android. content. res. typedArray; import android. OS. build; import android. util. attributeSet; import android. view. view; import android. view. viewGroup; import android. widget. compoundButton; import android. widget. linearLayout; // This class is copied from the source RadioGroup and added the recursive lookup subcontrol RadioButtonpublic class CustomNestRadioGrou. P extends LinearLayout {// holds the checked id; the selection is empty by defaultprivate int mCheckedId =-1; // tracks children radio buttons checked stateprivate CompoundButton. onCheckedChangeListener mChildOnCheckedChangeListener; // when true, mOnCheckedChangeListener discards eventsprivate boolean mProtectFromCheckedChange = false; private OnCheckedChangeListener mOnCheckedChangeListener; privat E PassThroughHierarchyChangeListener mPassThroughListener;/*** {@ inheritDoc} */public CustomNestRadioGroup (Context context) {super (context); init ();} /*** {@ inheritDoc} */public CustomNestRadioGroup (Context context, AttributeSet attrs) {super (context, attrs); init ();} private void init () {mCheckedId = View. NO_ID; // setOrientation (VERTICAL); // you can set the linear layout direction here: mChildOnCheckedChangeListener = new CheckedSt AteTracker (); mPassThroughListener = new PassThroughHierarchyChangeListener (); super. listener (mPassThroughListener);}/*** {@ inheritDoc} */@ Overridepublic void listener (OnHierarchyChangeListener listener) {// the user listener is delegated to our pass-through listener. mOnHierarchyChangeListener = listener;}/*** {@ inheritDoc} */@ Overridepro Tected void onFinishInflate () {super. onFinishInflate (); // checks the appropriate radio button as requested in the XML fileif (mCheckedId! = View. NO_ID) {mProtectFromCheckedChange = true; setCheckedStateForView (mCheckedId, true); mProtectFromCheckedChange = false; setCheckedId (mCheckedId );}} /** Recursively search for child controls with selected attributes */private static CompoundButton findCheckedView (View child) {if (child instanceof CompoundButton) return (CompoundButton) child; if (child instanceof ViewGroup) {ViewGroup group = (ViewGroup) child; for (int I = 0, j = group. getChildCo Unt (); I <j; I ++) {CompoundButton check = findCheckedView (group. getChildAt (I); if (check! = Null) return check ;}} return null; // not found} @ Overridepublic void addView (View child, int index, ViewGroup. layoutParams params) {final CompoundButton view = findCheckedView (child); if (view! = Null) {if (view. isChecked () {mProtectFromCheckedChange = true; if (mCheckedId! =-1) {setCheckedStateForView (mCheckedId, false);} mProtectFromCheckedChange = false; setCheckedId (view. getId () ;}} super. addView (child, index, params);}/*** <p> * Sets the selection to the radio button whose identifier is passed in * parameter. using-1 as the selection identifier clears the selection; * such an operation is equivalent to invoking {@ link # clearCheck ()}. * </p> ** @ param id * the un Ique id of the radio button to select in this group ** @ see # getCheckedRadioButtonId () * @ see # clearCheck () */public void check (int id) {// don't even botherif (id! =-1 & (id = mCheckedId) {return;} if (mCheckedId! =-1) {setCheckedStateForView (mCheckedId, false);} if (id! =-1) {setCheckedStateForView (id, true);} setCheckedId (id);} private void setCheckedId (int id) {mCheckedId = id; if (mOnCheckedChangeListener! = Null) {mOnCheckedChangeListener. onCheckedChanged (this, mCheckedId) ;}} private void setCheckedStateForView (int viewId, boolean checked) {View checkedView = findViewById (viewId); if (checkedView! = Null & checkedView instanceof CompoundButton) {(CompoundButton) checkedView ). setChecked (checked) ;}}/*** <p> * Returns the identifier of the selected radio button in this group. upon * empty selection, the returned value is-1. * </p> ** @ return the unique id of the selected radio button in this group ** @ see # check (int) * @ see # clearCheck () ** @ attr ref android. r. styleable # CustomNestRadioGr Oup_checkedButton */public int getCheckedRadioButtonId () {return mCheckedId;}/*** <p> * Clears the selection. when the selection is cleared, no radio button in * this group is selected and {@ link # getCheckedRadioButtonId ()} returns * null. * </p> ** @ see # check (int) * @ see # getCheckedRadioButtonId () */public void clearCheck () {check (-1 );} /*** <p> * Register a callback to be invoked when the che Cked radio button changes * in this group. * </p> ** @ param listener * the callback to call on checked state change */public void setOnCheckedChangeListener (OnCheckedChangeListener listener) {mOnCheckedChangeListener = listener ;} /*** {@ inheritDoc} */@ Overridepublic LayoutParams generateLayoutParams (AttributeSet attrs) {return new CustomNestRadioGroup. layoutParams (getContext (), attrs);}/*** {@ in HeritDoc} */@ Overrideprotected boolean checkLayoutParams (ViewGroup. layoutParams p) {return p instanceof CustomNestRadioGroup. layoutParams;} @ Overrideprotected LinearLayout. layoutParams generateDefaultLayoutParams () {return new LayoutParams (LayoutParams. WRAP_CONTENT, LayoutParams. WRAP_CONTENT);}/*** <p> * This set of layout parameters defaults the width and the height of the * children to {@ link # WR AP_CONTENT} when they are not specified in the XML * file. otherwise, this class ussed the value read from the XML file. * </p> ** <p> * See {@ link android. r. styleable # LinearLayout_Layout LinearLayout * Attributes} for a list of all child view attributes that this class * supports. * </p> **/public static class LayoutParams extends LinearLayout. layoutParams {/*** {@ inheritDoc} */public LayoutPa Rams (Context c, AttributeSet attrs) {super (c, attrs);}/*** {@ inheritDoc} */public LayoutParams (int w, int h) {super (w, h);}/*** {@ inheritDoc} */public LayoutParams (int w, int h, float initWeight) {super (w, h, initWeight);}/*** {@ inheritDoc} */public LayoutParams (ViewGroup. layoutParams p) {super (p);}/*** {@ inheritDoc} */public LayoutParams (MarginLayoutParams source) {super (source );} /*** <p> * Fixes the child's width to * {@ link android. view. viewGroup. layoutParams # WRAP_CONTENT} and the * child's height to * {@ link android. view. viewGroup. layoutParams # WRAP_CONTENT} when not * specified in the XML file. * </p> ** @ param a * the styled attributes set * @ param widthAttr * the width attribute to fetch * @ param heightAttr * the height attribute to fetch */@ Overrideprotected void setBaseAttrib Utes (TypedArray a, int widthAttr, int heightAttr) {if (. hasValue (widthAttr) {width =. getLayoutDimension (widthAttr, "layout_width");} else {width = WRAP_CONTENT;} if (. hasValue (heightAttr) {height =. getLayoutDimension (heightAttr, "layout_height") ;}else {height = WRAP_CONTENT ;}}} /*** <p> * Interface definition for a callback to be invoked when the checked radio * button changed in this group. * </P> */public interface OnCheckedChangeListener {/*** <p> * Called when the checked radio button has changed. when the selection * is cleared, checkedId is-1. * </p> ** @ param group * the group in which the checked radio button has changed * @ param checkedId * the unique identifier of the newly checked radio button */public void onCheckedChanged (CustomNestRadioGroup group, int checkedId);} p Rivate class implements callback. OnCheckedChangeListener {public void onCheckedChanged (CompoundButton buttonView, boolean isChecked) {// prevents from infinite recursionif (callback) {return;} Then = true; if (mCheckedId! =-1) {setCheckedStateForView (mCheckedId, false);} mProtectFromCheckedChange = false; int id = buttonView. getId (); setCheckedId (id) ;}}/*** <p> * A pass-through listener acts upon the events and dispatches them to * another listener. this allows the table layout to set its own internal * hierarchy change listener without preventing the user to setup his. * </p> */private class PassThroughHierarchyChan GeListener implementsViewGroup. onHierarchyChangeListener {private ViewGroup. onHierarchyChangeListener mOnHierarchyChangeListener;/*** {@ inheritDoc} */@ TargetApi (Build. VERSION_CODES.JELLY_BEAN_MR1) public void onChildViewAdded (View parent, View child) {if (parent = CustomNestRadioGroup. this) {CompoundButton view = findCheckedView (child); // find the child control if (view! = Null) {int id = view. getId (); // generates an id if it's missingif (id = View. NO_ID & Build. VERSION. SDK_INT> = Build. VERSION_CODES.JELLY_BEAN_MR1) {id = View. generateViewId (); view. setId (id);} view. setOnCheckedChangeListener (mChildOnCheckedChangeListener) ;}} if (mOnHierarchyChangeListener! = Null) {mOnHierarchyChangeListener. onChildViewAdded (parent, child) ;}}/*** {@ inheritDoc} */public void onChildViewRemoved (View parent, View child) {if (parent = CustomNestRadioGroup. this) {CompoundButton view = findCheckedView (child); // find the child control if (view! = Null) {view. setOnCheckedChangeListener (null) ;}} if (mOnHierarchyChangeListener! = Null) {mOnHierarchyChangeListener. onChildViewRemoved (parent, child );}}}}

This class is modified from the RadioGroup source code copy, and the RadioGroup method can be searched recursively. The Code has comments.

Ii. MainActivity

Package com. example. customgroupdemo; import android. OS. bundle; import android. app. activity; import android. view. menu; import android. widget. toast; import com. example. customgroupdemo. customNestRadioGroup; import com. example. customgroupdemo. customNestRadioGroup. onCheckedChangeListener; public class MainActivity extends Activity implements OnCheckedChangeListener {@ Overrideprotected void onCreate (Bundle saved InstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // modify the custom controls after the RadioGroup source code. You can find RadioButtonCustomNestRadioGroup CustomRadioGroup = (CustomNestRadioGroup) findViewById (R. id. customRadioGroup); if (CustomRadioGroup! = Null) CustomRadioGroup. setOnCheckedChangeListener (this) ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}@ Overridepublic void onCheckedChanged (CustomNestRadioGroup group, int checkedId) {group. check (checkedId); if (group. getId () = R. id. customRadioGroup) {if (checkedId = R. id. radio0) {Toast. makeText (getApplicationContext (), "select one", Toast. LENGTH_SHORT ). show ();} else if (checkedId = R. id. radio1) {Toast. makeText (getApplicationContext (), "select two", Toast. LENGTH_SHORT ). show ();} else if (checkedId = R. id. radio2) {Toast. makeText (getApplicationContext (), "select 3", Toast. LENGTH_SHORT ). show ();}}}}

The use of custom controls is mainly found by the complete package name and class name. You can see activity and xml to know how to call custom controls.

Example: com. example. customgroupdemo. CustomNestRadioGroup

Iii. xml

<LinearLayout 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" android: orientation = "vertical"> <ScrollView android: id = "@ + id/scrollView1" android: layout_width = "match_parent" android: layout_height = "wrap_content"> <LinearLayout android: layout_width = "match_parent" android: layout_height = "match_parent" android: orientation = "vertical"> <com. example. customgroupdemo. customNestRadioGroup android: id = "@ + id/CustomRadioGroup" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: orientation = "vertical"> <TextView android: id = "@ + id/textView1" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: gravity = "center" android: text = "first"/> <LinearLayout android: layout_width = "305dp" android: layout_height = "wrap_content" android: orientation = "horizontal"> <RadioButton android: id = "@ + id/radio0" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: checked = "true" android: text = "select one"/> <TextView android: id = "@ + id/textView1" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: gravity = "right" android: text = "first"/> </LinearLayout> <TextView android: id = "@ + id/textView1" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: gravity = "center" android: text = "second"/> <LinearLayout android: layout_width = "305dp" android: layout_height = "wrap_content" android: orientation = "horizontal"> <RadioButton android: id = "@ + id/radio1" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = ""/> <TextView android: id = "@ + id/textView1" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: gravity = "right" android: text = "second"/> </LinearLayout> <TextView android: id = "@ + id/textView1" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: gravity = "center" android: text = "third"/> <LinearLayout android: layout_width = "305dp" android: layout_height = "wrap_content" android: orientation = "horizontal"> <RadioButton android: id = "@ + id/radio2" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = ""/> <TextView android: id = "@ + id/textView1" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: gravity = "right" android: text = "third"/> </LinearLayout> </com. example. customgroupdemo. customNestRadioGroup> </LinearLayout> </ScrollView> </LinearLayout>
4. Check


Welcome to learn about various custom controls and source code.

Reprinted with the source: click here

Welcome to download the test demo: click here

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.