我正在Android Studio中开发一个应用程序,该应用程序从RealtimeDatabase Firebase获取数据,并且具有以下方法,我可以在首次运行时加载所有数据,但是当UI不变时更新数据库时,
>ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
MapModel shiftMap = ds.getValue(MapModel.class);
ViewGroup linearLayout = findViewById(R.id.mapLayout);
View cell = new View(MainActivity.this);
GradientDrawable shape = new GradientDrawable();
shape.setShape(GradientDrawable.RECTANGLE);
//shape.setColor(Color.rgb(33,150,243));
if (shiftMap.getOra00() ==1)
{
shape.setColor(Color.rgb(33,150,243));
}
else if (shiftMap.getOra00() ==0.5)
{
shape.setColor(Color.rgb(179,229,252));
}
else if (shiftMap.getOra00() ==0)
{
shape.setColor(Color.rgb(255,255,255));
}
shape.setStroke(3, Color.rgb(255,255,255));
shape.setCornerRadius(5);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
lp.setMargins(1, 1, 1, 1);
cell.setLayoutParams(lp);
cell.setBackground(shape);
linearLayout.addView(cell);
Log.i("Operator", shiftMap.getOperator() + " | " + shiftMap.getOra00() + " | " + shiftMap.getOra01() + " | " + shiftMap.getOra02());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
知道我在做什么错吗?
答案 0 :(得分:0)
我的代码存在的问题是,每次更新数据库时,它都会在UI中创建新控件。我设法通过删除每个控件然后更新UI来解决此问题,一切都很好。代码下方:
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
ViewGroup linearLayout = findViewById(R.id.mapLayout);
if(linearLayout.getChildCount() > 0)
linearLayout.removeAllViews();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
MapModel shiftMap = ds.getValue(MapModel.class);
View cell = new View(MainActivity.this);
GradientDrawable shape = new GradientDrawable();
shape.setShape(GradientDrawable.RECTANGLE);
//shape.setColor(Color.rgb(33,150,243));
if (shiftMap.getOra00() == 1)
{
shape.setColor(Color.rgb(33,150,243));
}
else if (shiftMap.getOra00() ==0.5)
{
shape.setColor(Color.rgb(179,229,252));
}
else if (shiftMap.getOra00() ==0)
{
shape.setColor(Color.rgb(255,255,255));
}
shape.setStroke(3, Color.rgb(255,255,255));
shape.setCornerRadius(5);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(70, 50);
lp.setMargins(1, 1, 1, 1);
cell.setLayoutParams(lp);
cell.setBackground(shape);
linearLayout.addView(cell);
Log.i("Operator", shiftMap.getOperator() + " | " + shiftMap.getOra00() + " | " + shiftMap.getOra01());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
代码:
ViewGroup linearLayout = findViewById(R.id.mapLayout);
if(linearLayout.getChildCount() > 0)
linearLayout.removeAllViews();
删除线性布局中的每个控件。