【问题标题】:Android: Adding multiple Views to a Linear Layout dynamicallyAndroid:动态地将多个视图添加到线性布局
【发布时间】:2012-11-01 06:44:32
【问题描述】:

我在这里检查了解决方案:

Adding multiple views of the same type

鉴于此,每次添加时都创建一个新视图,而不是只更改一个视图。

但我正在这样做:

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 创建一个新的充气器和视图。但我只得到最后一项。

ie..,只有 1 个 inflatedView,其中 tv1 为 -9,tv2 为 --9

似乎每次我进入 for 循环时,旧视图都会被新视图替换。如何添加所有 10 个视图??

谢谢你

【问题讨论】:

  • 您必须设置布局参数并为其添加规则...:)

标签: android textview


【解决方案1】:

我一般都用这个

private void renewDetail(){
        llDetail.removeAllViews();
        for (int i = 0; i < 10; i++) {
            llDetail.addView(new ChildDetailNotePieDiagram(context, "Name", 1000, 10));
        }
    }

逻辑是首先我从父布局中清除所有视图,然后将视图添加到父布局。

其中 llDetail 是线性布局,我创建了一个线性布局类 ChildDetailNotePieDiagram 并将其添加到线性布局中,因此基本上它与您现在使用的解决方案不同 但我想如果你愿意,你可以试试我的解决方案:) 如有任何问题,请在评论中提问

【讨论】:

  • 那么我可以在添加视图之前在for循环中使用它吗:((ViewGroup)cv.getParent()).removeView(cv);??
猜你喜欢
  • 2016-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-25
  • 1970-01-01
相关资源
最近更新 更多