`
JasonShieh
  • 浏览: 528488 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Android RadioGroup 换行, 支持多行多列

阅读更多
    经过反复试验,发现无论你怎么摆弄RadioGroup, 都无法实现多行多列的单选按钮组。
1. 如果不结合其他布局,例如LinearLayout, 则只能实现单行多个按钮组,或者单列多个按钮组。
2. 如果结合其他布局, 虽然可以实现多行多列的RadioButton布局,但是,如果不通过一些互斥算法,也无法实现按钮组的单选操作。


    所以,我对RadioGroup进行了改写.
/*
 * Copyright (C) 2006 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * 2013.11.06 updated by xiexiaojian 
 * Support that LinearLayouts or RadioButtons can be all RadioGroup's childrens,
 * we can display more rows and columns at the same time.
 */

package tv.pps.mobile.newipd.version3.custom.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;


/**
 * <p>This class is used to create a multiple-exclusion scope for a set of radio
 * buttons. Checking one radio button that belongs to a radio group unchecks
 * any previously checked radio button within the same group.</p>
 *
 * <p>Intially, all of the radio buttons are unchecked. While it is not possible
 * to uncheck a particular radio button, the radio group can be cleared to
 * remove the checked state.</p>
 *
 * <p>The selection is identified by the unique id of the radio button as defined
 * in the XML layout file.</p>
 *
 * <p><strong>XML Attributes</strong></p>
 * <p>See {@link android.R.styleable#RadioGroup RadioGroup Attributes}, 
 * {@link android.R.styleable#LinearLayout LinearLayout Attributes},
 * {@link android.R.styleable#ViewGroup ViewGroup Attributes},
 * {@link android.R.styleable#View View Attributes}</p>
 * <p>Also see
 * {@link android.widget.LinearLayout.LayoutParams LinearLayout.LayoutParams}
 * for layout attributes.</p>
 * 
 * @see RadioButton
 *
 */
public class RadioGroup extends LinearLayout {
    // holds the checked id; the selection is empty by default
    private int mCheckedId = -1;
    // tracks children radio buttons checked state
    private CompoundButton.OnCheckedChangeListener mChildOnCheckedChangeListener;
    // when true, mOnCheckedChangeListener discards events
    private boolean mProtectFromCheckedChange = false;
    private OnCheckedChangeListener mOnCheckedChangeListener;
    private PassThroughHierarchyChangeListener mPassThroughListener;

    /**
     * {@inheritDoc}
     */
    public RadioGroup(Context context) {
        super(context);
        setOrientation(VERTICAL);
        init();
    }

    /**
     * {@inheritDoc}
     */
    public RadioGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
        mCheckedId = View.NO_ID;

        final int index = VERTICAL;
        setOrientation(index);

        init();
    }

    private void init() {
        mChildOnCheckedChangeListener = new CheckedStateTracker();
        mPassThroughListener = new PassThroughHierarchyChangeListener();
        super.setOnHierarchyChangeListener(mPassThroughListener);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setOnHierarchyChangeListener(OnHierarchyChangeListener listener) {
        // the user listener is delegated to our pass-through listener
        mPassThroughListener.mOnHierarchyChangeListener = listener;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        // checks the appropriate radio button as requested in the XML file
        if (mCheckedId != -1) {
            mProtectFromCheckedChange = true;
            setCheckedStateForView(mCheckedId, true);
            mProtectFromCheckedChange = false;
            setCheckedId(mCheckedId);
        }
    }

    @Override
    public void addView(final View child, int index, ViewGroup.LayoutParams params) {
        if (child instanceof RadioButton) {
        	
        	((RadioButton) child).setOnTouchListener(new OnTouchListener() {
				
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					((RadioButton) child).setChecked(true);
					checkRadioButton((RadioButton) child);
					if(mOnCheckedChangeListener != null){
						mOnCheckedChangeListener.onCheckedChanged(RadioGroup.this, child.getId());
					}
					return true;
				}
			});
        	
        } else if(child instanceof LinearLayout){
        	int childCount = ((LinearLayout) child).getChildCount();
        	for(int i = 0; i < childCount; i++){
        		View view = ((LinearLayout) child).getChildAt(i);
        		if (view instanceof RadioButton) {
                    final RadioButton button = (RadioButton) view;

                	
                	((RadioButton) button).setOnTouchListener(new OnTouchListener() {
        				
        				@Override
        				public boolean onTouch(View v, MotionEvent event) {
        					((RadioButton) button).setChecked(true);
        					checkRadioButton((RadioButton) button);
        					if(mOnCheckedChangeListener != null){
        						mOnCheckedChangeListener.onCheckedChanged(RadioGroup.this, button.getId());
        					}
        					return true;
        				}
        			});
                    
                }
        	}
        }

        super.addView(child, index, params);
    }
    
    private void checkRadioButton(RadioButton radioButton){
    	View child;
    	int radioCount = getChildCount();
    	for(int i = 0; i < radioCount; i++){
    		child = getChildAt(i);
    		if (child instanceof RadioButton) {
    			if(child == radioButton){
    				// do nothing
    			} else {
    				((RadioButton) child).setChecked(false);
    			}
    		} else if(child instanceof LinearLayout){
    			int childCount = ((LinearLayout) child).getChildCount();
    			for(int j = 0; j < childCount; j++){
    				View view = ((LinearLayout) child).getChildAt(j);
    				if (view instanceof RadioButton) {
    					final RadioButton button = (RadioButton) view;
    	    			if(button == radioButton){
    	    				// do nothing
    	    			} else {
    	    				((RadioButton) button).setChecked(false);
    	    			}
    				}
    			}
    		}
    	}
    }

    /**
     * <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 unique id of the radio button to select in this group
     *
     * @see #getCheckedRadioButtonId()
     * @see #clearCheck()
     */
    public void check(int id) {
        // don't even bother
        if (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;
    }

    private void setCheckedStateForView(int viewId, boolean checked) {
        View checkedView = findViewById(viewId);
        if (checkedView != null && checkedView instanceof RadioButton) {
            ((RadioButton) 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#RadioGroup_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 checked 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}
     */
    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new RadioGroup.LayoutParams(getContext(), attrs);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
        return p instanceof RadioGroup.LayoutParams;
    }

    @Override
    protected LinearLayout.LayoutParams generateDefaultLayoutParams() {
        return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    }

    @Override
    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
        super.onInitializeAccessibilityEvent(event);
        event.setClassName(RadioGroup.class.getName());
    }

    @Override
    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
        super.onInitializeAccessibilityNodeInfo(info);
        info.setClassName(RadioGroup.class.getName());
    }

    /**
     * <p>This set of layout parameters defaults the width and the height of
     * the children to {@link #WRAP_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 LayoutParams(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
         */
        @Override
        protected 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 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(RadioGroup group, int checkedId);
    }

    private class CheckedStateTracker implements CompoundButton.OnCheckedChangeListener {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // prevents from infinite recursion
            if (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 class PassThroughHierarchyChangeListener implements
            ViewGroup.OnHierarchyChangeListener {
        private ViewGroup.OnHierarchyChangeListener mOnHierarchyChangeListener;

        /**
         * {@inheritDoc}
         */
        public void onChildViewAdded(View parent, View child) {
            if (parent == RadioGroup.this && child instanceof RadioButton) {
                int id = child.getId();
                // generates an id if it's missing
                if (id == View.NO_ID) {
                    id = child.hashCode();
                    child.setId(id);
                }
                ((RadioButton) child).setOnCheckedChangeListener(
                        mChildOnCheckedChangeListener);
            }

            if (mOnHierarchyChangeListener != null) {
                mOnHierarchyChangeListener.onChildViewAdded(parent, child);
            }
        }

        /**
         * {@inheritDoc}
         */
        public void onChildViewRemoved(View parent, View child) {
            if (parent == RadioGroup.this && child instanceof RadioButton) {
                ((RadioButton) child).setOnCheckedChangeListener(null);
            }

            if (mOnHierarchyChangeListener != null) {
                mOnHierarchyChangeListener.onChildViewRemoved(parent, child);
            }
        }
    }
}



其中的这一段是关键改写代码:
       @Override
    public void addView(final View child, int index, ViewGroup.LayoutParams params) {
        if (child instanceof RadioButton) {
        	
        	((RadioButton) child).setOnTouchListener(new OnTouchListener() {
				
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					((RadioButton) child).setChecked(true);
					checkRadioButton((RadioButton) child);
					if(mOnCheckedChangeListener != null){
						mOnCheckedChangeListener.onCheckedChanged(RadioGroup.this, child.getId());
					}
					return true;
				}
			});
        	
        } else if(child instanceof LinearLayout){
        	int childCount = ((LinearLayout) child).getChildCount();
        	for(int i = 0; i < childCount; i++){
        		View view = ((LinearLayout) child).getChildAt(i);
        		if (view instanceof RadioButton) {
                    final RadioButton button = (RadioButton) view;

                	
                	((RadioButton) button).setOnTouchListener(new OnTouchListener() {
        				
        				@Override
        				public boolean onTouch(View v, MotionEvent event) {
        					((RadioButton) button).setChecked(true);
        					checkRadioButton((RadioButton) button);
        					if(mOnCheckedChangeListener != null){
        						mOnCheckedChangeListener.onCheckedChanged(RadioGroup.this, button.getId());
        					}
        					return true;
        				}
        			});
                    
                }
        	}
        }

        super.addView(child, index, params);
    }
    
    private void checkRadioButton(RadioButton radioButton){
    	View child;
    	int radioCount = getChildCount();
    	for(int i = 0; i < radioCount; i++){
    		child = getChildAt(i);
    		if (child instanceof RadioButton) {
    			if(child == radioButton){
    				// do nothing
    			} else {
    				((RadioButton) child).setChecked(false);
    			}
    		} else if(child instanceof LinearLayout){
    			int childCount = ((LinearLayout) child).getChildCount();
    			for(int j = 0; j < childCount; j++){
    				View view = ((LinearLayout) child).getChildAt(j);
    				if (view instanceof RadioButton) {
    					final RadioButton button = (RadioButton) view;
    	    			if(button == radioButton){
    	    				// do nothing
    	    			} else {
    	    				((RadioButton) button).setChecked(false);
    	    			}
    				}
    			}
    		}
    	}
    }


布局文件我就不贴出来了。

实现结果如下图:

3
0
分享到:
评论
11 楼 nielong123 2016-05-23  
nielong123 写道
onCheckedChanged(MultiRadioGroup group, int checkedId) 


  checkedId 都是 -1


不好意思   忘记设RadioButton的id了  失误
10 楼 nielong123 2016-05-23  
onCheckedChanged(MultiRadioGroup group, int checkedId) 


  checkedId 都是 -1
9 楼 zk_Ming 2016-04-23  
zk_Ming 写道
我用了你的,但是radiogroup 点击事件失效?

看懂啦,谢谢大神
8 楼 zk_Ming 2016-04-23  
chaozhidan 写道
有木有源码啊,谢谢大神,646869341@qq.com

你用啦么?radiobutton的点击事件是是否失效?
7 楼 zk_Ming 2016-04-23  
我用了你的,但是radiogroup 点击事件失效?
6 楼 diyangxia 2015-06-25  
估计是没处理内嵌纵向LinearLayout布局
5 楼 chaozhidan 2014-08-05  
有木有源码啊,谢谢大神,646869341@qq.com
4 楼 shensens 2014-05-05  
你好,按照你的布局,会报错的……我的环境是4.2。能否给个可运行的例子?我方便学习下
3 楼 JasonShieh 2013-12-24  
harichen 写道
harichen 写道
你好,可以把布局文件给我看一下吗?我不知到怎么用啊

我的邮件是499077848@qq.com,谢谢!

布局类似下面:
<RadioGroup>

  <LinearLayout >
      <RadioButton />
      <RadioButton />
</LinearLayout>

  <LinearLayout >
      <RadioButton />
      <RadioButton />
</LinearLayout>

</RadioGroup>
2 楼 harichen 2013-12-10  
harichen 写道
你好,可以把布局文件给我看一下吗?我不知到怎么用啊

我的邮件是499077848@qq.com,谢谢!
1 楼 harichen 2013-12-10  
你好,可以把布局文件给我看一下吗?我不知到怎么用啊

相关推荐

    Android-支持多行多列等复杂布局的RadioGroup

    然而,原生的RadioGroup仅支持单行排列,这在需要多行多列展示选项时显得功能有限。`Multi_RadioGroup_Plus`就是为了解决这一问题而设计的,它扩展了原生RadioGroup的功能,提供了更灵活的布局方式。 `Multi_...

    RadioGroup支持RadioButton多行多列

    总结一下,`RadioGroup` 支持 `RadioButton` 的多行多列布局,通过设置不同的布局组件和属性,我们可以自由地调整 `RadioButton` 的排列方式。同时,通过设置 `OnCheckedChangeListener`,我们可以轻松获取用户在 `...

    RadioGroup多行多列

    要在RadioGroup中创建多行多列,可以使用子布局(如LinearLayout)来实现。每个子布局可以视为一行,然后在子布局中添加RadioButton。例如: ```xml &lt;RadioGroup android:id="@+id/radio_group" android:...

    换行的RadioGroup可以使用

    1. **自定义布局**:为了实现换行效果,可以为`RadioGroup`指定一个自定义布局(如`LinearLayout`或`GridLayout`),并设置对应的布局参数,例如`android:orientation="vertical"`,使单选按钮垂直排列。通过调整`...

    多行多列radioGroup

    自定义MultilineGroup类,实现radiogroup多行多列单选效果,继承了LinearLayout,在MultilineGroup下面可以放置多个RadioGroup标签,即实现多行多列单选效果。

    Android多行多列的单选按钮组的实现

    本教程将详细介绍如何在Android应用中实现一个多行多列的`RadioGroup`,以提供更加灵活和美观的用户界面。 首先,我们需要了解`RadioGroup`的基本用法。`RadioGroup`继承自`LinearLayout`,所以它可以按垂直或水平...

    RadioButton实现多行多列单选

    3. **排列方式**:为了实现多行多列,你可能需要在`RadioGroup`中使用嵌套的`LinearLayout`或其他布局管理器。例如,可以使用两个`LinearLayout`,一个用于行,另一个用于列。这样,`RadioButton`就可以按照你想要的...

    RadioGroup换行

    这个工具类写好的可以直接拿来用,可以换行多列使用,不影响单个选择

    Android RadioGroup多行显示效果 解决单选问题

    问题是Android的RadioButton是一般是放在RadioGroup中进行管理的,而RadioGroup又是线性布局,即单行有效,多行无效。如图那种就需要两个RadioGroup来进行合作。那么如果进行合作呢? 分析:RadioGroup多行显示其实...

    可多行的RadioGroup

    在Android开发中,`RadioGroup`控件通常用于创建单选按钮组,用户只能选择其中的一个选项。然而,标准的`RadioGroup`默认是水平排列的,这在选项过多时可能会导致一行显示不下,影响用户体验。针对这种情况,我们...

    RadioGroup

    总结,RadioGroup在Android开发中扮演着重要角色,它提供了管理单选按钮的功能,并支持多行多列的布局,可以根据需求调整布局方式,实现复杂但用户友好的选择界面。通过合理的布局设计和事件监听,我们可以构建出...

    支持多行的radiogroup

    针对android的一个只支持向下一层迭代radiogButton的radiogroup的改进

    Android自定义View之RadioGroup实现跨多行显示

    Android 自定义 View 之 RadioGroup 实现跨多行显示 Android 开发中,RadioGroup 是一个常用的控件,用于实现单选操作。但是, RadioGroup 默认情况下只能在一行中显示选项,无法跨多行显示。这对一些需要在多行中...

    listview多行多列单选

    "listview多行多列单选"指的是在一个ListView中实现每一行可以被选择,同时支持多列展示的特性。这种功能通常应用于如通讯录、菜单列表等场景,用户可以逐个选择列表中的项。以下是对这个主题的详细讲解: 1. **...

    Android 自定义RadioGroup布局,修改源码自定义控件

    `RadioGroup`是Android系统中用于管理多个单选按钮(`RadioButton`)的容器,通常限制用户只能选择其中一项。 首先,理解`RadioGroup`的工作原理至关重要。`RadioGroup`默认使用线性布局,如水平或垂直方向,将`...

    android可换行的单选效果

    在Android开发中,创建一个可换行的单选效果是一个常见的需求,特别是在设计用户界面时,需要让多个单选按钮(RadioButton)在布局中自动换行以适应屏幕大小。本篇将详细介绍如何实现这种效果,主要涉及`RadioGroup`...

    RadioGroup实现单选框的多行排列

    然后,我们可以将多个 RadioGroup 组合起来,实现多行排列的效果。 下面是实现多行排列的示例代码: 首先,我们定义两个 RadioGroup,以实现两行排列: ```xml &lt;RadioGroup android:id="@+id/radio1" android:...

    Android:解决RadioGroup中RadioButton的图片自定义及每项间隔距离一样

    在Android开发中,RadioGroup和RadioButton是常用的组件,用于实现单选功能。本文将深入探讨如何自定义RadioButton的图片以及确保RadioGroup中的每个RadioButton之间的间隔距离保持一致。首先,我们来了解一下这两个...

Global site tag (gtag.js) - Google Analytics