有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

当有多行时,java将RadioButton和EditText对齐在同一行上

我试图创建一个小列表(3行),其中水平排列的每行上有一个RadioButton和一个EditText视图。我希望单选按钮位于相同的RadioGroup。我无法将单选按钮和编辑文本视图添加到linearlayout,因为Android会大喊该单选按钮有另一个父项。我怎样才能解决这个问题

我以编程方式添加每一行:

mAnswerGroup.addView(radioButton, new RadioGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
mAnswerGroup.addView(editText, new RadioGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

共 (1) 个答案

  1. # 1 楼答案

    在这种情况下,RadioGroup将不起作用。您必须手动处理3RadioButtons的已检查更改,因为您需要进行线性布局并在其中添加RadioButtonEditText。您必须手动取消选中其他单选按钮

    设置每个RadioButton的onCheckedChangeListener并手动处理: 在活动中实现OnCheckedChangeListener接口,并在onCreate()中执行此操作:

    rb_1.setOnCheckedChangeListener(this);
    rb_2.setOnCheckedChangeListener(this);
    rb_3.setOnCheckedChangeListener(this);
    

    然后,重写接口的onCheckedChanged()方法:

    @Override
        public void onCheckedChanged(CompoundButton cb, boolean isChecked) {
            if(isChecked){
                //get the id of the checked button for later reference
                int id = cb.getId();
    
                /*
                * do what you want here based on the id you got
                */
    
                //uncheck the other RadioButtons
                rb_1.setChecked(id == R.id.rb_1);
                rb_2.setChecked(id == R.id.rb_2);
                rb_3.setChecked(id == R.id.rb_3);
    
            }
        }