Android Custom Radiogroup Layouts

Source: Internet
Author: User

This effect is required in the previous time project, customizing the Radiogroup layout, but only if the RadioButton is to be found. I collect all kinds of information and try various tests. Finally, there is a custom radiogroup layout. The self- defined radiogroup layout, which can contain various layouts, RadioButton also in the layout of the surface. The ID of the RadioButton can be found through the recursive lookup method, or a group. Next look at the code.

Reprint please specify the source: click here

Welcome to download Test Demo: Click here

One, custom Customnestradiogroup 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 source Radiogroup copied out, added recursive lookup child control Radiobuttonpublic class Customnestradiogroup extends LinearLayout {//holds the checked Id The selection is empty by defaultprivate int mcheckedid = -1;//Tracks Children radio buttons checked Stateprivate Compoun Dbutton.oncheckedchangelistener mchildoncheckedchangelistener;//When True, Moncheckedchangelistener discards Eventsprivate Boolean mprotectfromcheckedchange = False;private Oncheckedchangelistener moncheckedchangelistener; Private 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); Here you can set the linear layout direction Mchildoncheckedchangelistener = new Checkedstatetracker (); mpassthroughlistener = new Passthroughhierarchychangelistener (); Super.setonhierarchychangelistener (Mpassthroughlistener);} /** * {@inheritDoc} */@Overridepublic void Setonhierarchychangelistener (Onhierarchychangelistener listener) {//the User listener is delegated to our pass-through Listenermpassthroughlistener.monhierarchychangelistener = listener;} /** * {@inheritDoc} */@Overrideprotected 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 finds a child control with a checked property */private static Compoundbutton Findcheckedview (View children) {if (son instanceof CompoundButton) return (Compoundbutton) child;if (child instanceof ViewGroup) {viewgroup group = (viewgroup) child;for (int i = 0, j = Group.getchildcount (); 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 compoundbut ton view = Findcheckedview (Child), if (view! = null) {if (view.ischecked ()) {Mprotectfromcheckedchange = True;if (Mcheckedi D! =-1) {Setcheckedstateforview (Mcheckedid, false);} Mprotectfromcheckedchange = False;setcheckedid (View.getid ());}} Super.addview (Child, index, params);} /** * <p> * Sets the selection to the radio button whose identifier are passed in * parameter. Using-1 as the selection identifier clears the selection; * Such an operation was equivalent to invoking {@link #clearCheck ()}. * </p> * * @param ID * The unique 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 = = MCh Eckedid)) {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); 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 #clearChec K () * * @attr ref Android. R.styleable#customnestradiogroup_checkedbutton */publicint Getcheckedradiobuttonid () {return mcheckedid;} /** * <p> * clears the selection. When the selection are 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 being invoked when the checked radio button changes * in this group. * </p> * * @param listener * The callback to call on checked state change */public void Setoncheckedchan Gelistener (Oncheckedchangelistener listener) {Moncheckedchangelistener = listener;} /** * {@inheritDoc} */@Overridepublic layoutparams generatelayoutparams (AttributeSet attrs) {return new Customnestradiogroup.layoutparams (GetContext (), attrs);} /** * {@inheritDoc} */@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 #WRAP_CONTEN T} When they is not specified in the XML * file. Otherwise, this class ussed the value of the read from the XML file. * </p> * * <p> * See {@link Android. R.styleable#linearlayout_layout linearlayout * Attributes} for a list of all child view Attributes the This class * Suppo Rts. * </p> * */public static class Layoutparams extends Linearlayout.layoutparams {/** * {@inheritDoc} */public LAYOUTP Arams (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 (marginlayoutparamsSOURCE) {super (source);} /** * <p> * Fixes The child's width to * {@link android.view.viewgroup.layoutparams#wrap_content} and the * child ' s The height to * {@link android.view.viewgroup.layoutparams#wrap_content} is not * specified in the XML file. * </p> * * @param a * The styled attributes set * @param widthattr * The width attribute to f  Etch * @param heightattr * The height attribute to fetch */@Overrideprotected void Setbaseattributes (TypedArray A, int widthattr,int heightattr) {if (A.hasvalue (widthattr)) {width = a.getlayoutdimension (widthattr, "layout_width");} else {width = wrap_content;} if (A.hasvalue (heightattr)) {height = a.getlayoutdimension (heightattr, "layout_height");} else {height = wrap_content;}}}  /** * <p> * Interface definition for a callback to being 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 grou p, int checkedid);} Private class Checkedstatetracker Implementscompoundbutton.oncheckedchangelistener {public void oncheckedchanged ( Compoundbutton Buttonview,boolean isChecked) {//Prevents from infinite recursionif (mprotectfromcheckedchange) {return ;} Mprotectfromcheckedchange = 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 classPassthroughhierarchychangelistener 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);//Lookup Sub-control if (view = null) {int id = View.getid ();//generates an ID if it ' s M Issingif (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) {C Ompoundbutton view = Findcheckedview (child);//Find sub-control if (view! = null) {View.setoncheckedchangelistener (null);}} if (monhierarchYchangelistener! = null) {monhierarchychangelistener.onchildviewremoved (parent, Child);}}} 

This class is from the Radiogroup source copy out to modify, to increase the downward recursive lookup Radiogroup method can be. The code has comments.

Second, 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 savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main);//Modify the Radiogroup source after the custom control, Can find radiogroup inside different layouts 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 PR Esent.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 Three", Toast.length_short). Show ();}}}

the use of custom controls, mainly through the full package name plus the class name to find, you can see the activity and XML can know how to invoke the custom control.

Example: Com.example.customgroupdemo.CustomNestRadioGroup

Third, 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:orien        tation= "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.cus Tomgroupdemo.                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 "/> <line                    Arlayout 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_con Tent "android:checked=" true "android:text=" select one "/> &lt ;                        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:orienta                        tion= "Horizontal" > <radiobutton android:id= "@+id/radio1"                        Android:layout_width= "Wrap_content" android:layout_height= "Wrap_content"                        android:text= "Choose Two"/> <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"/&G                T                    <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=" select three "/> <textview Andro Id:id= "@+id/textview1" android:layout_width= "Match_parent" android:layout_he              ight= "Wrap_content" android:gravity= "right" android:text= "third"/>  </LinearLayout> </com.example.customgroupdemo.CustomNestRadioGroup> </LinearLayout> </ScrollView></LinearLayout>
Four, see


Welcome to Exchange Learning various custom controls, source learning.

Reprint please specify the source: click here

Welcome to download Test Demo: Click here

Android Custom Radiogroup Layouts

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.