正如标题所描述的那样,我正在尝试将一个3x3单选按钮网格组合成一个单一的无线电组。在之前的一个问题中,我了解到,对于与单个组相对应的单选按钮,他们必须是他们将对应的无线电组的直接子项。当我试图在一个广播组中封装整个表格布局(在表行中使用单选按钮)时,我学到了很多。
跑进那堵墙,我尝试了以下方法:
<TableLayout android:id="@+id/table_radButtons"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/title_radGroup_buffer">
<TableRow>
<RadioGroup android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="@+id/radGroup1">
<RadioButton android:id="@+id/rad1"
android:text="Button1"
android:layout_width="105px"
android:layout_height="wrap_content"
android:textSize="13px"></RadioButton>
<RadioButton android:id="@+id/rad2"
android:text="Button2"
android:layout_width="105px"
android:textSize="13px"
android:layout_height="wrap_content"></RadioButton>
<RadioButton android:id="@+id/rad3"
android:text="Button3"
android:layout_width="105px"
android:textSize="13px"
android:layout_height="wrap_content"></RadioButton>
</RadioGroup>
</TableRow>
<TableRow>
<RadioGroup android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="@+id/radGroup1">
<!-- snippet -->
</TableRow>
<!-- snippet --->
</TableLayout>
显然我第一次没有学习,因为我又遇到了一堵墙。我希望不同表行中的单选按钮会注意到它们是同一个无线电组的一部分(给每个组提供相同的ID),但这不起作用。
有什么方法可以将所有这些按钮分组到一个单独的无线电组中,并且仍然保持我的3x3结构(每行3行,3个单选按钮)?
答案 0 :(得分:65)
实际上,如果你像本例中那样继承TableLayout
/**
*
*/
package com.codtech.android.view;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RadioButton;
import android.widget.TableLayout;
import android.widget.TableRow;
/**
* @author diego
*
*/
public class ToggleButtonGroupTableLayout extends TableLayout implements OnClickListener {
private static final String TAG = "ToggleButtonGroupTableLayout";
private RadioButton activeRadioButton;
/**
* @param context
*/
public ToggleButtonGroupTableLayout(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
/**
* @param context
* @param attrs
*/
public ToggleButtonGroupTableLayout(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
@Override
public void onClick(View v) {
final RadioButton rb = (RadioButton) v;
if ( activeRadioButton != null ) {
activeRadioButton.setChecked(false);
}
rb.setChecked(true);
activeRadioButton = rb;
}
/* (non-Javadoc)
* @see android.widget.TableLayout#addView(android.view.View, int, android.view.ViewGroup.LayoutParams)
*/
@Override
public void addView(View child, int index,
android.view.ViewGroup.LayoutParams params) {
super.addView(child, index, params);
setChildrenOnClickListener((TableRow)child);
}
/* (non-Javadoc)
* @see android.widget.TableLayout#addView(android.view.View, android.view.ViewGroup.LayoutParams)
*/
@Override
public void addView(View child, android.view.ViewGroup.LayoutParams params) {
super.addView(child, params);
setChildrenOnClickListener((TableRow)child);
}
private void setChildrenOnClickListener(TableRow tr) {
final int c = tr.getChildCount();
for (int i=0; i < c; i++) {
final View v = tr.getChildAt(i);
if ( v instanceof RadioButton ) {
v.setOnClickListener(this);
}
}
}
public int getCheckedRadioButtonId() {
if ( activeRadioButton != null ) {
return activeRadioButton.getId();
}
return -1;
}
}
并创建一个这样的布局(当然你需要清理它,但你有了想法)
<?xml version="1.0" encoding="utf-8"?>
<com.codtech.android.view.ToggleButtonGroupTableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:id="@+id/radGroup1">
<TableRow>
<RadioButton android:id="@+id/rad1" android:text="Button1"
android:layout_width="105px" android:layout_height="wrap_content"
android:textSize="13px" />
<RadioButton android:id="@+id/rad2" android:text="Button2"
android:layout_width="105px" android:textSize="13px"
android:layout_height="wrap_content" />
<RadioButton android:id="@+id/rad3" android:text="Button3"
android:layout_width="105px" android:textSize="13px"
android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<RadioButton android:id="@+id/rad1" android:text="Button1"
android:layout_width="105px" android:layout_height="wrap_content"
android:textSize="13px" />
<RadioButton android:id="@+id/rad2" android:text="Button2"
android:layout_width="105px" android:textSize="13px"
android:layout_height="wrap_content" />
<RadioButton android:id="@+id/rad3" android:text="Button3"
android:layout_width="105px" android:textSize="13px"
android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<RadioButton android:id="@+id/rad1" android:text="Button1"
android:layout_width="105px" android:layout_height="wrap_content"
android:textSize="13px" />
<RadioButton android:id="@+id/rad2" android:text="Button2"
android:layout_width="105px" android:textSize="13px"
android:layout_height="wrap_content" />
<RadioButton android:id="@+id/rad3" android:text="Button3"
android:layout_width="105px" android:textSize="13px"
android:layout_height="wrap_content" />
</TableRow>
</com.codtech.android.view.ToggleButtonGroupTableLayout>
答案 1 :(得分:8)
在上面https://stackoverflow.com/a/2383978/5567009回答之后我得到了另一个解决这个问题的方法,我添加了一些其他功能,比如,保存组的状态以及清除检查功能的功能,如无线电组。
import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.IdRes;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TableLayout;
import android.widget.TableRow;
public class RadioGridGroup extends TableLayout implements View.OnClickListener {
private static final String TAG = "ToggleButtonGroupTableLayout";
private int checkedButtonID = -1;
/**
* @param context
*/
public RadioGridGroup(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
/**
* @param context
* @param attrs
*/
public RadioGridGroup(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
@Override
public void onClick(View v) {
if (v instanceof RadioButton) {
int id = v.getId();
check(id);
}
}
private void setCheckedStateForView(int viewId, boolean checked) {
View checkedView = findViewById(viewId);
if (checkedView != null && checkedView instanceof RadioButton) {
((RadioButton) checkedView).setChecked(checked);
}
}
/* (non-Javadoc)
* @see android.widget.TableLayout#addView(android.view.View, int, android.view.ViewGroup.LayoutParams)
*/
@Override
public void addView(View child, int index,
android.view.ViewGroup.LayoutParams params) {
super.addView(child, index, params);
setChildrenOnClickListener((TableRow) child);
}
/* (non-Javadoc)
* @see android.widget.TableLayout#addView(android.view.View, android.view.ViewGroup.LayoutParams)
*/
@Override
public void addView(View child, android.view.ViewGroup.LayoutParams params) {
super.addView(child, params);
setChildrenOnClickListener((TableRow) child);
}
private void setChildrenOnClickListener(TableRow tr) {
final int c = tr.getChildCount();
for (int i = 0; i < c; i++) {
final View v = tr.getChildAt(i);
if (v instanceof RadioButton) {
v.setOnClickListener(this);
}
}
}
/**
* @return the checked button Id
*/
public int getCheckedRadioButtonId() {
return checkedButtonID;
}
/**
* Check the id
*
* @param id
*/
public void check(@IdRes int id) {
// don't even bother
if (id != -1 && (id == checkedButtonID)) {
return;
}
if (checkedButtonID != -1) {
setCheckedStateForView(checkedButtonID, false);
}
if (id != -1) {
setCheckedStateForView(id, true);
}
setCheckedId(id);
}
/**
* set the checked button Id
*
* @param id
*/
private void setCheckedId(int id) {
this.checkedButtonID = id;
}
public void clearCheck() {
check(-1);
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
this.checkedButtonID = ss.buttonId;
setCheckedStateForView(checkedButtonID, true);
}
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState savedState = new SavedState(superState);
savedState.buttonId = checkedButtonID;
return savedState;
}
static class SavedState extends BaseSavedState {
int buttonId;
/**
* Constructor used when reading from a parcel. Reads the state of the superclass.
*
* @param source
*/
public SavedState(Parcel source) {
super(source);
buttonId = source.readInt();
}
/**
* Constructor called by derived classes when creating their SavedState objects
*
* @param superState The state of the superclass of this view
*/
public SavedState(Parcelable superState) {
super(superState);
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(buttonId);
}
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
并在XML中使用此内容,如下所示
<com.test.customviews.RadioGridGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TableRow android:layout_marginTop="@dimen/preview_five">
<RadioButton
android:id="@+id/rad1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1" />
<RadioButton
android:id="@+id/rad2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2" />
</TableRow>
<TableRow android:layout_marginTop="@dimen/preview_five">
<RadioButton
android:id="@+id/rad3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button3" />
<RadioButton
android:id="@+id/rad4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button4" />
</TableRow>
<TableRow android:layout_marginTop="@dimen/preview_five">
<RadioButton
android:id="@+id/rad5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button5" />
<RadioButton
android:id="@+id/rad6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button6" />
</TableRow>
<TableRow android:layout_marginTop="@dimen/preview_five">
<RadioButton
android:id="@+id/rad7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button7" />
<RadioButton
android:id="@+id/rad8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button8" />
</TableRow>
</com.test.customviews.RadioGridGroup>
如有任何其他改进,请发表评论。
答案 2 :(得分:3)
您唯一的选择是将源代码抓取到RadioGroup
并尝试在TableLayout
或其他内容中复制其功能。否则无法创建RadioButtons
的3x3网格。幸运的是,RadioButton
类不了解RadioGroup
- 所有互斥逻辑都在RadioGroup
中。因此,应该可以创建一个RadioGrid
或者其他东西......但这将是一项非常多的工作。
答案 3 :(得分:2)
RadioGroup以下列方式扩展..
java.lang.Object
↳ android.view.View
↳ android.view.ViewGroup
↳ android.widget.LinearLayout
↳ android.widget.RadioGroup
如果您需要在网格布局中排列单选按钮,则可能需要构建自己的自定义代码,该代码从GridLayout
扩展。
答案 4 :(得分:1)
我编写了一个非常简单的filename = 'example.vip'
子类,其行为类似于GridLayout
。看起来是这样:
要使用它,请首先添加RadioGroup
库:
GridLayout
然后复制粘贴implementation "androidx.gridlayout:gridlayout:1.0.0-beta01"
子类:
GridLayout
最后使用它:
**
* A GridLayout subclass that acts like a RadioGroup. Important: it only accepts RadioButton as children.
* Inspired by https://stackoverflow.com/a/2383978/4034572
*/
class GridRadioGroup @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : GridLayout(context, attrs, defStyleAttr), View.OnClickListener {
@IdRes var selectedRadioButtonId: Int? = null
get() = getSelectedRadioButton()?.id
private set
private fun getSelectedRadioButton(): RadioButton? {
for (index in 0 until childCount) {
val radioButton = getChildAt(index) as RadioButton
if (radioButton.isChecked) return radioButton
}
return null
}
override fun onClick(view: View) {
// While this looks inefficient, it does fix a bug (2 RadioButtons could be selected at the
// same time) when navigating back by popping-up a fragment from the backstack.
for (index in 0 until childCount) {
val radioButton = getChildAt(index) as RadioButton
radioButton.isChecked = false
}
val radioButton = view as RadioButton
radioButton.isChecked = true
}
override fun addView(child: View?, index: Int, params: ViewGroup.LayoutParams?) {
super.addView(child, index, params)
child?.setOnClickListener(this)
}
}
样式:
<com.example.ui.GridRadioGroup
android:id="@+id/gridRadioGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:columnCount="2"
>
<RadioButton
android:id="@+id/option_1"
style="@style/GridRadioButton"
android:drawableTop="@drawable/option_1"
android:text="@string/register_choose_goal_option_1"
app:layout_columnWeight="1"
app:layout_rowWeight="1"
/>
<RadioButton
android:id="@+id/option_2"
style="@style/GridRadioButton"
android:drawableTop="@drawable/option_2"
android:text="@string/option_2"
app:layout_columnWeight="1"
app:layout_rowWeight="1"
tools:checked="true"
/>
<RadioButton
android:id="@+id/option_3"
style="@style/GridRadioButton"
android:drawableTop="@drawable/option_3"
android:text="@string/option_3"
app:layout_columnWeight="1"
app:layout_rowWeight="1"
tools:checked="true"
/>
<RadioButton
android:id="@+id/option_4"
style="@style/GridRadioButton"
android:drawableTop="@drawable/preparar_carrera"
android:text="@string/option_4"
app:layout_columnWeight="1"
app:layout_rowWeight="1"
/>
</com.example.ui.GridRadioGroup>
代码很简单,但是对我来说很好用。如果您想要更完整的内容(例如使用<style name="GridRadioButton">
<item name="android:layout_width">0dp</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_margin">10dp</item>
<item name="android:background">@drawable/button_option_background_selector</item>
<item name="android:drawablePadding">16dp</item>
<item name="android:button">@null</item>
<item name="android:gravity">center_horizontal</item>
<item name="android:padding">20dp</item>
<item name="android:textColor">@drawable/text_button_option_color_selector</item>
<item name="android:textSize">14sp</item>
</style>
),则可以使用check this alternative implementation,它显然更加精细,并且与OnCheckedChangeListener
相当。< / p>
答案 5 :(得分:0)
它是一个淤泥,但为什么不呢为什么不只使用九个RadioGroups,或三个水平RadioGroups,每个都有三个按钮。然后可以将每个无线电组与gridView或relativeLayout等对齐。
然后使用RadioButton的标准OnCheckedChangeListener而不是使用属于CompoundButton的那个(同名)。
然后,当按下任何RadioButton时,您可以使用无线电组取消选择单选按钮。然后以编程方式选择单击的单选按钮。
这是一个可怕的解决方案,但它可以像人们希望的那样工作。
以下是一些示例代码,我使用2x2按钮布局来执行此操作。
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
updateList(Hurricane.ELEVATION_ALL);
watermarkAdapter = new WatermarkAdapter(getActivity(), R.layout.watermark_item,
relatedHurricanes);
setListAdapter(watermarkAdapter);
this.getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
this.getView().setBackgroundResource(R.drawable.splash_screen1);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
View v = this.getView();
filterGroup1 = (RadioGroup)v.findViewById(R.id.filter_rg1);
filterGroup2 = (RadioGroup)v.findViewById(R.id.filter_rg2);
filterGroup3 = (RadioGroup)v.findViewById(R.id.filter_rg3);
filterGroup4 = (RadioGroup)v.findViewById(R.id.filter_rg4);
rb1 = (RadioButton) v.findViewById(R.id.first_radio_button);//All
rb2 = (RadioButton) v.findViewById(R.id.second_radio_button);//0-6
rb4 = (RadioButton) v.findViewById(R.id.third_radio_button);//6-12
rb3 = (RadioButton) v.findViewById(R.id.fourth_radio_button);//>=5
rb1.setOnCheckedChangeListener(this);
rb2.setOnCheckedChangeListener(this);
rb3.setOnCheckedChangeListener(this);
rb4.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
filterGroup1.clearCheck();
filterGroup2.clearCheck();
filterGroup3.clearCheck();
filterGroup4.clearCheck();
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this.getActivity());
int cid = buttonView.getId();
Editor editor = prefs.edit();
int elevation = Hurricane.ELEVATION_ALL;
//All
if(rb1.getId() == cid){
elevation = Hurricane.ELEVATION_ALL;
}
//0-6
else if(rb2.getId() == cid){
elevation = Hurricane.ELEVATION_6to12;
}
//6-12
else if(rb3.getId() == cid){
elevation = Hurricane.ELEVATION_0to6;
}
//>=12
else if(rb4.getId() == cid){
elevation = Hurricane.ELEVATION_GT12;
}
update(StormFragment.NORMAL, elevation);
}
答案 6 :(得分:0)
我会选择嵌套的RadioGroups。根RadioGroup将具有垂直方向,其子节点将是三个具有水平方向的RadioGroup。
<RadioGroup
android:orientation="vertical">
<RadioGroup
android:id="@+id/rg_1"
android:orientation="horizontal">
<RadioButton />
<RadioButton />
<RadioButton />
</RadioGroup>
<RadioGroup
android:id="@id/rg_2"
android:orientation="horizontal">
<RadioButton />
<RadioButton />
<RadioButton />
</RadioGroup>
<RadioGroup
android:id="@+id/rg_3"
android:orientation="horizontal">
<RadioButton />
<RadioButton />
<RadioButton />
</RadioGroup>
</RadioGroup>
每个chield RadioGroup都有一个ID,它将由java验证方法中的RadioGroup对象调用。像这样:
RadioGroup rg_1 = (RadioGroup) findViewById(R.id.rg_1);
RadioGroup rg_2 = (RadioGroup) findViewById(R.id.rg_2);
RadioGroup rg_3 = (RadioGroup) findViewById(R.id.rg_3);
现在只需在交换机案例中使用clearCheck()
,您就可以清除其他两个RadioGroup的检查。像这样:
case R.id.radioButton_1:
if (checked) {
rg_2.clearCheck();
rg_3.clearCheck();
}
break;
答案 7 :(得分:0)
这使用具有RadioGroup功能的自定义GridLayout。谢谢 Saikrishnan Ranganathan for saiaspire/RadioGridGroup
<com.sample.RadioGridGroup
xmlns:grid="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
grid:columnCount="3"
grid:useDefaultMargins="true">
<android.support.v7.widget.AppCompatRadioButton
android:checked="true"
android:text="Text1"
grid:layout_columnWeight="1"/>
<android.support.v7.widget.AppCompatRadioButton
android:text="Text2"
grid:layout_columnWeight="1"/>
<android.support.v7.widget.AppCompatRadioButton
android:text="Text3"
grid:layout_columnWeight="1"/>
<android.support.v7.widget.AppCompatRadioButton
android:text="Text4"
grid:layout_columnWeight="1"/>
<android.support.v7.widget.AppCompatRadioButton
android:text="Text5"
grid:layout_columnWeight="1"/>
<android.support.v7.widget.AppCompatRadioButton
android:text="Text6"
grid:layout_columnWeight="1"/>
<android.support.v7.widget.AppCompatRadioButton
android:text="Text7"
grid:layout_columnWeight="1"/>
<android.support.v7.widget.AppCompatRadioButton
android:text="Text8"
grid:layout_columnWeight="1"/>
<android.support.v7.widget.AppCompatRadioButton
android:text="Text9"
grid:layout_columnWeight="1"/>
</com.sample.RadioGridGroup>
答案 8 :(得分:0)
在我看来,一种更简单的方法是使用 RecyclerView
。
ViewHolder
将只包含一个 RadioButton
。
data class
将包含要显示的 string
属性,以及用于切换 boolean
状态的附加 isChecked
属性。
在 ViewHolder
内,我们将在 onClickListener
内切换状态。
RecyclerViewAdapter
将包含一个附加函数来获取所选项目。
data class BloodType(val name: String, var isChecked: Boolean)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/rb_item_blood_type"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:text="RadioButton"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
class BloodTypeAdapter(val data: List<BloodType>) :
RecyclerView.Adapter<BloodTypeAdapter.BloodTypeHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BloodTypeHolder {
val view =
LayoutInflater.from(parent.context).inflate(R.layout.item_blood_type, parent, false)
return BloodTypeHolder(view)
}
override fun onBindViewHolder(holder: BloodTypeHolder, position: Int) {
holder.itemView.rb_item_blood_type.isChecked = data[position].isChecked
holder.itemView.rb_item_blood_type.text = data[position].name
}
override fun getItemCount(): Int {
return data.size
}
/**
* @return The selected item from the list.
*/
fun getCheckedItem(): BloodType {
data.forEach {
if (it.isChecked) {
return it
}
}
return data[0]
}
inner class BloodTypeHolder(view: View) : RecyclerView.ViewHolder(view) {
init {
itemView.rb_item_blood_type.setOnClickListener {
data.forEachIndexed { index, bloodType ->
bloodType.isChecked = index == adapterPosition
}
notifyDataSetChanged()
}
}
}
}
//...
private fun initializeBloodTypeRecyclerView() {
rvBloodType.layoutManager = GridLayoutManager(context, 2)
val bloodTypes = mutableListOf<BloodType>()
bloodTypes.apply {
add(BloodType("A+", true))
add(BloodType("A-", false))
add(BloodType("B+", false))
//...
}
val bloodTypeAdapter = BloodTypeAdapter(bloodTypes)
rvBloodType.adapter = bloodTypeAdapter
}
//...