动态添加的复选框仅显示最后一个值

时间:2017-12-21 17:25:21

标签: android

这是我的代码,只导致员工列表的最后一个值

 public void addCheckBoxesView()
     {
         Employee ee;
         CheckBox chkbox;
         ArrayList<Employee> employee_list= initEmployees();
         for(int i =0; i<employee_list.size();i++)
         {
             ee = (Employee) employee_list.get(i);
             chkbox = new CheckBox(this);
             chkbox.setId(ee.getID());
             chkbox.setText(ee.getName());
             layout.addView(chkbox);
         }
     }

2 个答案:

答案 0 :(得分:1)

Try this

布局文件

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/my_root"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">


    </LinearLayout>

MainActivity.xml

    LinearLayout rootLayout = (LinearLayout) findViewById(R.id.my_root);
    LinearLayout sublayout = new LinearLayout(this);
    sublayout.setOrientation(LinearLayout.HORIZONTAL);


    Employee ee;
    CheckBox chkbox;
    ArrayList<Employee> employee_list = new ArrayList<>();
    Employee employee=new Employee();
    employee.setId(1);
    employee.setName("as");
    employee_list.add(employee);

    Employee bb=new Employee();
    bb.setId(4);
    bb.setName("siva");
    employee_list.add(bb);


    Employee hsud=new Employee();
    hsud.setId(16);
    hsud.setName("kumar");
    employee_list.add(hsud);


    for (int i = 0; i < employee_list.size(); i++) {
        ee = (Employee) employee_list.get(i);
        chkbox = new CheckBox(this);
        chkbox.setId(ee.getId());
        chkbox.setText(ee.getName());
        sublayout.addView(chkbox);
    }
    rootLayout.addView(sublayout);

Employee.xml

    class Employee {
        int id;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        String name;
    }

答案 1 :(得分:0)

如果有效,请尝试下面的内容。

public void addCheckBoxesView()
     {
         ArrayList<Employee> employee_list= initEmployees();
         for(Employee ee : employee_list)
         {
             CheckBox chkbox = new CheckBox(this);
             chkbox.setId(ee.getID());
             chkbox.setText(ee.getName());
             layout.addView(chkbox);
         }
     }