如何在运行时添加相同的视图

问题描述 投票:-2回答:2

我想设计一个这样的视图

enter image description here

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

android android-studio android-recyclerview layout-inflater
2个回答
0
投票

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

<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
                }
            }

0
投票

好吧创建一个Model类:

 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 Adapter中使用这个arraylist:

ArrayList<Product> productList = new ArrayList<Product>

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

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

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

因为以后如果你想设置值,你可以轻松地使用位置,并且在点击提交时你可以只取整个列表

© www.soinside.com 2019 - 2024. All rights reserved.