【问题标题】:Firebase onDataChange create new view in ConstraintLayoutFirebase onDataChange 在 ConstraintLayout 中创建新视图
【发布时间】:2017-06-25 13:05:09
【问题描述】:

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

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

这是我的代码:

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

【问题讨论】:

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


    【解决方案1】:

    不确定我是否做得正确,我最终在约束布局中添加了一个列表视图,并使用自定义数组适配器将我的数据绑定到列表视图。

    向导:https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-15
      • 1970-01-01
      • 2014-12-15
      • 1970-01-01
      • 1970-01-01
      • 2019-08-17
      相关资源
      最近更新 更多