【问题标题】:How can i get the tag of the checkboxes after they are checked?选中后如何获取复选框的标签?
【发布时间】:2017-01-11 01:08:30
【问题描述】:

我试过这个:

private int[] intCheckBox = {
        R.id.monCheck,
        R.id.tueCheck,
        R.id.wedCheck
};

private CheckBox[] realCheckBox = new CheckBox[intCheckBox.length];

private int i;

然后:

 for (i=0;i<intCheckBox.length;i++){
        realCheckBox[i] = (CheckBox) findViewById(intCheckBox[i]);
        realCheckBox[i].setTag(i);
        realCheckBox[i].setOnCheckedChangeListener(showFinal);
    }

}

private CompoundButton.OnCheckedChangeListener showFinal = new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        String outPut2 = "";

        if (realCheckBox[i].isChecked()){
            outPut2 += realCheckBox[i].getTag();
            outPutText3.setText(outPut2);

        }

但是,当我运行应用程序时,在我选中其中一个框后显示错误,错误是:

E/AndroidRuntime: FATAL EXCEPTION: main
              java.lang.ArrayIndexOutOfBoundsException: length=3; index=3

我知道还有另一种方法可以通过逐个设置来获取标签甚至字符串...但是,我想使用数组来显示标签,以便进行进一步的编码以获得“whatIReallyWantToGet”的 int 值:

 java.util.Calendar cal = java.util.Calendar.getInstance();
        cal.set(Calendar.MONTH, position);
        cal.set(Calendar.DAY_OF_WEEK, whatIReallyWantToGet);
        cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
        int month = cal.get(Calendar.MONTH);
        String output = "";
        while (cal.get(Calendar.MONTH) == month) {
            output += cal.get(Calendar.DAY_OF_MONTH) + "/" + (cal.get(Calendar.MONTH) + 1) + ",";
            cal.add(Calendar.DAY_OF_MONTH, 7);
        }

我在网上搜索了很长时间。但是没有用。我只是教科书和在线资源的新手。请帮助或尝试提供一些想法如何实现这一目标。非常感谢!

【问题讨论】:

    标签: android android-studio checkbox


    【解决方案1】:

    从您分享的代码来看,在我看来您并没有重置变量 i 的值。

    这可以解释为什么异常说您正在尝试访问数组的索引 3

    E/AndroidRuntime: 致命异常: main java.lang.ArrayIndexOutOfBoundsException: length=3;索引=3

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-13
      • 2020-08-25
      • 1970-01-01
      • 2011-12-22
      • 2014-03-07
      相关资源
      最近更新 更多