【问题标题】:Swap positions of Radios - Android java交换 Radios 的位置 - Android java
【发布时间】:2014-04-22 23:08:46
【问题描述】:

我有一个 RadioGroup 和四个 Radio。

    RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup);

    RadioButton r0 = (RadioButton) findViewById(R.id.radio0);
    RadioButton r1 = (RadioButton) findViewById(R.id.radio1);
    RadioButton r2 = (RadioButton) findViewById(R.id.radio2);
    RadioButton r3 = (RadioButton) findViewById(R.id.radio3);

我将文本设置为所有这些。

    r0.setText("1");
    r1.setText("2");
    r2.setText("3");
    r3.setText("4");

所以我得到了像这样的收音机 1、2、3、4。我怎样才能随机交换收音机的位置。我想得到这样的东西 3,2,1,4 或 2,3,1,4....等... 但重要的是,我不想更改收音机的文本,因为我说过我想交换位置。

【问题讨论】:

    标签: java android radio-button


    【解决方案1】:

    我认为您无法使用相同的布局 XML 文件来实现这一点。

    使用 4 种不同的布局,并随机膨胀。

    如果您在每个 XML 文件中保持相同的 ID,您的所有 ID 将始终有效。

    @Override
    public void onCreate(final Bundle bundle) {
      super.onCreate(bundle);
      setContentView(randomLayout());
    
      RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup);
      // ...
    }
    
    public static int randomLayout() {
      final int n[] = { R.layout.layout1, R.layout.layout2, R.layout.layout3, R.layout.layout4 }
      Random random = new Random();
      return n[random.nextInt(n.length)];
    }
    

    【讨论】:

    • 这只是一个例子。每个可能的订单都需要 1 个 XML。据我所知,你不能轻易地做到这一点。另一种选择是使用RelativeLayouts ...
    • 据我计算,应该有 24 种组合。但实际上我需要这种交换,因为其中一台收音机将是真正的答案,其他 3 台是错误的。所以我需要交换正确答案的位置,错误答案并不重要,所以4个组合就可以了。 --> TFFF, FTFF, FFTF, FFFT --> 非常感谢 :)
    【解决方案2】:

    很快: 如果你没有任何想法, 试试这种方式

    类似...

    int n = nb of radios;
    
    RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup);
    
    RadioButton r0 = new RadioButton(this);
    RadioButton r1 = new RadioButton(this);
    RadioButton rn = new RadioButton(this);
    
    r0.setId(/*idr0*/);
    r1.setId(/*idr1*/);
    rn.setId(/*idrn*/);
    
    r0.setText("text0");
    rn.setText("textn");
    
    ArrayList<RadioButton> e = new ArrayList<RadioButton>();
    e.add(r0);
    e.add(rn);
    
    Random rand = new Random();
    
    while(n<0)
    {
     int i = rand.nextInt(n);
    
     if (e.get(i) != null)
     { 
       rg.add(e.get(i));
       e.remove(i);
       n--;
     }
    }
    

    【讨论】:

    • 第二个“列表”出现错误 --> List e = new List(); --> 无法实例化类型 List
    • setId() 是我没有想到的解决方案。这很聪明,即使我不喜欢从代码中操作 ID,但仍然:好点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-15
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多