简体   繁体   English

LinearLayout中Checkbox的最佳解决方案

[英]Best solution for Checkbox in LinearLayout

In my LinearLayout, there's a variable number of CheckBoxes. 在我的LinearLayout中,有可变数量的CheckBoxes。 In a question I had a month ago someone said it´s better to add checkboxes dynamicly instead of make them not visible. 在一个月前的一个问题中,有人说,最好动态添加复选框,而不是使其不可见。

Integer[] count = new Integer[]{1,2,3,4,5,6,7,8,9,10};
size = mFrageList.get(position).getAuswahlList().size();
for (int i = 0; i < size; i++) {

    cBox = new CheckBox(this);
    cBox.setText(mFrageList.get(position).getAuswahlList().get(i));
    cBox.setId(count[i]);
    cBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

           if(isChecked){
                antwortencode[position] += "" + buttonView.getId();
                frageBeantworten.setText("Antwort :"+antwortencode[position]+" abgeben");

            } else {
                 String id = Integer.toString(buttonView.getId());
                 antwortencode[position] = antwortencode[position].replaceAll(id,"");
                 if(!antwortencode[position].isEmpty() || antwortencode[position]!= "") {
                     frageBeantworten.setText("Antwort :" + antwortencode[position] + " abgeben");
                  } else {
                      frageBeantworten.setText("Keine Checkbox(en) gewählt");
                  }
           }
       }
});

antworten.addView(cBox);

Currently, I'm able to save a string with the checked checkboxes, if I un-check a checkbox, it deletes it's value out of the string. 目前,我能够保存一个带有选中复选框的字符串,如果我取消选中一个复选框,它将从字符串中删除它的值。 If I update the activity, the string is saved, and the checkboxes get a new List from the mFrageList.get(position)getAuswahlList(); 如果我更新活动,则将保存字符串,并且复选框将从mFrageList.get(position)getAuswahlList();中获取新列表。 and fill a new string in the "antwortencode" List with their values. 并将其值填充到“ antwortencode”列表中的新字符串。

If I go back to the last position, I have the string which was generated but the checkboxes aren't checked anymore. 如果返回到最后一个位置,则将生成一个字符串,但是不再选中该复选框。 But they have the Strings from the old position. 但是它们具有旧位置的弦乐。 that means everything is saved except the state of the checkboxes. 这意味着除了复选框的状态外,所有内容均已保存。 I cant set a cBox.setChecked(isChecked) or buttonView.setChecked(isChecked) or buttonView.setChecked(buttonView.isChecked()) or something which is nearly the same in syntax. 我无法设置cBox.setChecked(isChecked)或buttonView.setChecked(isChecked)或buttonView.setChecked(buttonView.isChecked())或语法上几乎相同的东西。

I don't know what I can do besides declaring 10 Checkboxes in a xml file to talk to them one by one and set the VISIBLE.false if the auswahlList.get(position).isEmpty(). 除了在xml文件中声明10个复选框以与它们逐一对话并设置aviswahlList.get(position).isEmpty()设置VISIBLE.false外,我不知道该怎么办。

IMPORTANT: My XML is a Scrollable Activity because the size of the content overextended the screen. 重要说明:我的XML是可滚动活动,因为内容的大小超出了屏幕的范围。 Thats why i didn´t and can´t use a Listview. 那就是为什么我没有也不能使用Listview的原因。 So i need a solution that uses a LinearLayout 所以我需要一个使用LinearLayout的解决方案

The truth is, you should actually use a ListView . 事实是,您实际上应该使用ListView As long as you reuse a layout multiple times - do it. 只要您多次重复使用布局-便要这样做。

There are 2 options: 有2个选项:

The other thing is how to maintain the state of Checkboxes - use model classes. 另一件事是如何维护Checkboxes的状态-使用模型类。 It's extremely easy with a ListView as it forces you to use an Adapter which provides methods to iterate over all positions. 使用ListView非常容易,因为它迫使您使用Adapter ,该Adapter提供了遍历所有位置的方法。

Example of an adapter: 适配器示例:

public class CheckableItemAdapter extends BaseAdapter {

private List<Pair<Integer, Boolean>> items = new ArrayList<>();

public void setItems(List<Pair<Integer, Boolean>> items) {
    this.items = items;
}

@Override
public int getCount() {
    return items.size();
}

@Override
public Object getItem(int position) {
    return items.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view;
    ViewHolder holder;
    if (convertView == null) {
        view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_checkable, parent, false);
        holder = new ViewHolder(view);
        view.setTag(holder);
    } else {
        view = convertView;
        holder = (ViewHolder) view.getTag();
    }
    Pair<Integer, Boolean> item = items.get(position);
    holder.itemCheck.setChecked(item.second);
    return view;
}

static class ViewHolder {

    CheckBox itemCheck;

    public ViewHolder(View itemView) {
        itemCheck = (CheckBox) itemView.findViewById(R.id.check);
    }
}
}

I´ve managed to solve my problem alone, and now i want to share it, even if it isn´t the best example of programming. 我设法独自解决了我的问题,现在我想分享它,即使它不是编程的最佳示例。

  Integer[] count = new Integer[]{1,2,3,4,5,6,7,8,9,10}; //maximum of 10 Checkboxes
        size = mFrageList.get(position).getAuswahlList().size();
        for (int i = 0; i < size; i++) {
            cBox = new CheckBox(this);
            cBox.setText(mFrageList.get(position).getAuswahlList().get(i));
            cBox.setId(count[i]);

            try{ //this is where the magic happens
                if(antwortencode[position] != ""){ //cause i won´t want null in my db i´ve set "" as standard string in my activity for the List<String>
                    String code = antwortencode[position];
                    char[] c = code.toCharArray();
                    for(int j=0;j<=c.length;j++){
                        int x = c[j] -'0'; // 'char 1' - 'char 0' = Integer 1 , lol
                        if(cBox.getId()== x){ //compare them
                            cBox.toggle(); //if it fits, toggle
                        }
                    }
                }
            } catch (Exception e){
                    e.printStackTrace();
            } //and here it ends

            cBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                    if(isChecked){
                        antwortencode[position] += "" + buttonView.getId();
                        frageBeantworten.setText("Antwort :"+antwortencode[position]+" abgeben");

                    } else {
                        String id = Integer.toString(buttonView.getId());
                        antwortencode[position] = antwortencode[position].replaceAll(id,"");
                        if(!antwortencode[position].isEmpty() || antwortencode[position]!= "") {
                            frageBeantworten.setText("Antwort :" + antwortencode[position] + " abgeben");
                        } else {
                            frageBeantworten.setText("Keine Checkbox(en) gewählt");
                        }
                    }
                }
            });

            antworten.addView(cBox);

Ty for the answers and for the correction of my question. 请输入答案和更正我的问题。 Nostramärus Nostramärus

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM