【问题标题】:how to use custom layout in existing layout using dynamic linearlayout如何使用动态线性布局在现有布局中使用自定义布局
【发布时间】:2016-10-09 16:14:10
【问题描述】:

您好,我正在开发一个应用程序,我想在我的卡片视图中从现有布局扩展布局。我想根据我的字符串数组动态显示文本视图列表。

这是我现有的布局

我想在上述布局的最后一个卡片视图中为以下布局充气

所以尝试使用编码来做到这一点,但它只显示一个文本视图

我的编码如下 但它不工作它只显示一个文本视图 我想根据我的字符串大小动态添加 textview

我想像 listview 一样膨胀布局,但我不想使用 listview。我想在没有 listview 的情况下动态实现这一点

【问题讨论】:

    标签: android android-linearlayout textview dynamic-view


    【解决方案1】:

    它只显示一个文本视图我想动态添加文本视图 根据我的字符串大小

    可能是由于每次为每个 TextView 膨胀 inflate_specification 并在 for 循环中初始化 container

    这样做:

    LinearLayout container = (LinearLayout)findViewById(R.id.temp);
    LayoutInflater inflater = (LayoutInflater) getApplicationContext().
                          getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    
    for(int i=0;i<5;i++)
      {  
         View view = inflater.inflate(R.layout.inflate_specification, container,false);
         // Create TextView
          TextView product = (TextView)view.findViewById(R.id.speci);
           product.setText("i= " + i);
    
           container.addView(view);
      }
    

    【讨论】:

    • @unknownapk:查看我的编辑答案以及按照我的答案执行时会发生什么?
    【解决方案2】:

    试试这个代码:

    LinearLayout container = (LinearLayout)findViewById(R.id.temp);
    LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    container.removeAllViews();
    for(int i=0;i<5;i++) {
        View view = inflater.inflate(R.layout.inflate_specification, container,false);
        // Create TextView
        TextView product = (TextView)findViewById(R.id.speci);
    
        product.setText("i= " + i);
    
        container.addView(view);
    
     }
    

    【讨论】:

    • 因为你必须在循环中声明容器,请参阅我的代码,否则它会覆盖
    • 然后我使用表格布局通过动态添加rowview来显示它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多