我在这里检查了解决方案:
Adding multiple views of the same type
鉴于此,每次添加时都创建一个新 View ,而不是只更改 1 个 View 。
但我正在这样做:
for (int i = 0; i < 10; i++) {
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(
CommentsActivity.LAYOUT_INFLATER_SERVICE);
View cv = vi.inflate(R.layout.item, null);
TextView textView1 = (TextView) cv.findViewById(R.id.tv1);
textView1.setText("-" + i);
TextView textView2 = (TextView) cv.findViewById(R.id.tv2);
textView2.setText("--" + i);
LinearLayout insertPoint = (LinearLayout) findViewById(R.id.layout);
insertPoint.addView(cv, 0, new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
}
这就像为每个 i 创建一个新的充气器和 View 。但我只得到最后一项。
即..,只有 1 个 inflatedView,tv1 为 -9,tv2 为 --9
似乎每次我进入 for 循环时,旧 View 都会被新 View 替换。如何添加所有 10 个 View ??
谢谢
最佳答案
我一般用这个
private void renewDetail(){
llDetail.removeAllViews();
for (int i = 0; i < 10; i++) {
llDetail.addView(new ChildDetailNotePieDiagram(context, "Name", 1000, 10));
}
}
逻辑是首先清除父布局中的所有 View ,然后将 View 添加到父布局。
其中 llDetail 是一个线性布局,我创建了一个线性布局类 ChildDetailNotePieDiagram 并将其添加到线性布局中,所以基本上它与您现在使用的解决方案不同 但我认为您可以根据需要尝试我的解决方案 :) 随时在评论中提出有关此的任何问题
关于Android:动态地将多个 View 添加到线性布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13172221/