RadioGroup扩展RelativeLayout?

问题描述 投票:7回答:3

我想为我的应用程序制作一个单选按钮网格,我所了解到的是,使用常规的 "相对布局"(RelativeLayout)是不可能的。RadioGroup 因为它扩展了LinearLayout,如果你试图安排好了 RadioButtons 使用RelativeLayout INSIDE的 RadioGroupRadioGroup 不见得 Buttons 里面 RelativeLayout.

所以为了解决这个问题,我想做一个自定义的RadioGroup,扩展RelativeLayout而不是LinearLayout。

我该怎么做呢?

更新:我按你说的做了,但我在类文件中出现了这些错误,我不知道如何修复。

Description Resource    Path    Location    Type
RadioGroup_checkedButton cannot be resolved or is not a field   RadioGroupRelative.java /BlockBall/src/com/stickfigs/blockball  line 81 Java Problem
The constructor RelativeLayout.LayoutParams(int, int, float) is undefined   RadioGroupRelative.java /BlockBall/src/com/stickfigs/blockball  line 265    Java Problem
The method setOnCheckedChangeWidgetListener(CompoundButton.OnCheckedChangeListener) is undefined for the type RadioButton   RadioGroupRelative.java /BlockBall/src/com/stickfigs/blockball  line 363    Java Problem
The method setOnCheckedChangeWidgetListener(null) is undefined for the type RadioButton RadioGroupRelative.java /BlockBall/src/com/stickfigs/blockball  line 377    Java Problem
VERTICAL cannot be resolved to a variable   RadioGroupRelative.java /BlockBall/src/com/stickfigs/blockball  line 68 Java Problem
Widget_CompountButton_RadioButton cannot be resolved or is not a field  RadioGroupRelative.java /BlockBall/src/com/stickfigs/blockball  line 79 Java Problem
java android xml radio-button radio-group
3个回答
9
投票

你需要得到 RadioGroup的源代码 此处的所有条目,取代 LinearLayoutRelativeLayout.

将这段代码添加到你的项目中的某个xml文件中(通常它的名字是attrs.xml)。

<resources>
    <declare-styleable name="RadioGroup">
        <attr name="android:checkedButton" />
    </declare-styleable>
</resources>

替换 RadioGroup的构造函数。

public RadioGroup(Context context) {
    super(context);
    if (!isInEditMode()) {
        init();
    }
}

public RadioGroup(Context context, AttributeSet attrs) {
    super(context, attrs);
    if (!isInEditMode()) {
        TypedArray attributes = context.obtainStyledAttributes(
                attrs, R.styleable.RadioGroup, 0,
                android.R.style.Widget_CompoundButton_RadioButton);

        int value = attributes.getResourceId(R.styleable.RadioGroup_checkedButton,
            View.NO_ID);
        if (value != View.NO_ID) {
            mCheckedId = value;
        }

        attributes.recycle();
        init();
    }
}

删除以下构造函数 LayoutParams 内类。

public LayoutParams(int w, int h, float initWeight) {
    super(w, h, initWeight);
}

替换所有出现的 setOnCheckedChangeWidgetListener() 的方法调用。setOnCheckedChangeListener() 方法。重要的是: 在这种情况下,不可能从使用这个部件的代码中使用这个方法。

还没有试过,但希望这能行得通。


2
投票

将RadioGroup的源代码从 此处 并编辑它,把它改成扩展RelativeLayout而不是LinearLayout。


0
投票

这不在主题范围内,但如果你想用以下方法做同样的事情 ConstraintLayout 那么代码就是 可在Github上下载

您可以导入库并使用小部件。ConstraintRadioGroup

© www.soinside.com 2019 - 2024. All rights reserved.