Firebase onDataChange在ConstraintLayout

时间:2017-06-25 13:05:09

标签: android android-layout firebase-realtime-database android-constraintlayout

我是Android开发和Firebase的新手。我正在寻找一种简单的方法来完成以下简单的工作:

  1. 从Firebase数据库中检索数据
  2. 从数据
  3. 创建复选框列表

    这是我的代码:

    protected void AttachFirebaseListner(){
        DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("data");
        ValueEventListener listener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                int i = 0;
                for (DataSnapshot child : dataSnapshot.getChildren()) {
                    String guid = child.getKey();
                    DataObjects.Box box = child.getValue(DataObjects.Box.class);
                    CreateCheckBox(i,guid,box);
                    i++;
                }
            }
    
            @Override
            public void onCancelled(DatabaseError databaseError) {
    
            }
        };
        ref.addListenerForSingleValueEvent(listener);
    }
    

    和创建复选框的功能:

    protected void CreateCheckBox(int seq, String guid, DataObjects.Box box){
        ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.constraintLayout);
        int currentID = 100+seq;
        int previousID = 100+(seq-1);
    
        ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.leftToLeft = PARENT_ID;
        if (seq == 0) { //first
            layoutParams.topToTop = PARENT_ID;
        }
        else {
            layoutParams.topToBottom = previousID;
        }
    
        CheckBox chkBox= new CheckBox(getApplicationContext());
        chkBox.setId(currentID);
        chkBox.setTag(guid);
        chkBox.setLayoutParams(layoutParams);
        chkBox.setText(box.name);
    
        layout.addView(chkBox);
    
        ConstraintSet set = new ConstraintSet();
        set.clone(layout);
        if (seq == 0) { //first
            set.connect(chkBox.getId(), ConstraintSet.TOP, layout.getId(), ConstraintSet.TOP);
        }
        else {
            set.connect(chkBox.getId(), ConstraintSet.TOP, previousID, ConstraintSet.BOTTOM);
        }
        set.applyTo(layout);
    }
    

    但是,似乎onDataChange方法是异步的,因此不会填充复选框。

    这样做的正确方法是什么?

    由于 CL

1 个答案:

答案 0 :(得分:0)

不确定我是否正确完成,我最终在约束布局中添加了listview,并使用自定义数组适配器将我的数据绑定到listview。

指南:explains how to automate this with package managers and build tools