【问题标题】:how to add same view on runtime如何在运行时添加相同的视图
【发布时间】:2017-12-28 05:39:57
【问题描述】:

我想设计一个这样的视图

相同的视图重复多次,即当点击 add item 时,它应该添加相同的视图(一开始应该只有一行)。我不明白如何制作一个,似乎我无法使用 RecyclerView 制作这样的视图。也许我可以使用 LayoutInflater 制作一个。但是怎么做?

【问题讨论】:

标签: android android-studio android-recyclerview layout-inflater


【解决方案1】:

是的,您可以使用 Layout Inflator 添加它:

<ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:id="@+id/main_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
        </LinearLayout>
    </ScrollView>

活动中:

LinearLayout linearLayout = findViewById(R.id.main_container);
                LinearLayout childLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.child_layout, null, false);
                childLayout.setTag(linearLayout.getChildCount() + 1); // set some Id
                linearLayout.addView(childLayout); // Adding for first time
                for(int i=0; i<5; i++) {
                    childLayout.setTag(linearLayout.getChildCount() + 1);
                    linearLayout.addView(childLayout); //child_layout is your row layout design
                }

检索:

 JSONObject jsonObject = new JSONObject();
            for (int i = 0; i < linearLayout.getChildCount(); i++) {
                View childLayout = linearLayout.getChildAt(i);
                if (childLayout instanceof LinearLayout) {
                    //get SubViews of you child_layout and get thos value 
                    // for id int id = (int) childLayout.getTag()
                    //add the values to jsonObject
                }
            }

【讨论】:

  • 你的回答很有道理,但是我需要重复这个视图的次数取决于用户点击的次数。你能提供代码吗?
  • 我想在按钮的 OnClick 事件中添加这个
  • 是的,您可以编写一个函数来添加一个布局。所以当用户点击添加按钮时调用该函数
  • 所以只要放 linearLayout.addView(childLayout);在 onClick 会做吗?
  • 可以,先试试看有没有问题
【解决方案2】:

创建一个模型类:

 public  class Product{
     int product_id;
     int product_size;
     int product_qty;

        //provide all the getter setters and constructor
         public Product(int product_id,int product_size,int product_qty){
                this.product_id = product_id;
                this.product_size = product_size;
                this.product_qty = product_qty;
         }
       }

现在在 Recyclerview 适配器中使用这个数组列表:

ArrayList<Product> productList = new ArrayList<Product>

点击添加按钮时,只需在此列表中添加虚拟值,例如:

   productList.add(new Product(0,0,0));

在您的 recyclerview 适配器内部提供您选择的布局

因为稍后如果您想设置值,您可以轻松地使用位置进行设置,并且在单击提交时您可以获取整个列表

【讨论】:

  • class 都是小写字母,Java 有专门的命名约定(请避免在变量名中使用下划线)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-03
  • 1970-01-01
  • 2019-02-20
  • 1970-01-01
相关资源
最近更新 更多