【问题标题】:Can't set RecyclerView inside CardView?不能在 CardView 中设置 RecyclerView?
【发布时间】:2021-09-26 13:07:31
【问题描述】:

我正在尝试将 RecyclerView 放入 CardView 并动态创建项目。

显然,在XML 中,RecyclerView 设置在CardView tag 内部,但如您所见,RecyclerView 项目是在CardView 外部创建的。

RecyclerView's items是照片中kgset表示的部分。而CardView也是另一个RecyclerView的一个项目。)

有什么问题?

XML

<androidx.cardview.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="12dp"
    android:layout_marginLeft="12dp"
    android:layout_marginRight="12dp"
    app:cardElevation="10dp">
    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:id="@+id/ll1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintTop_toTopOf="parent">
            <TextView
                android:id="@+id/workout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="8dp"
                android:text="TEST"/>
            <View
                android:layout_width="match_parent"
                android:layout_height="2dp"
                android:background="@color/light_blue_400"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/ll2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintTop_toBottomOf="@+id/ll1">

            <com.google.android.material.button.MaterialButton
                android:id="@+id/delete"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:layout_marginStart="8dp"
                android:layout_marginEnd="4dp"
                style="@style/RoutineButtonStyle"
                android:text="DELETE"
                app:icon="@drawable/ic_delete"/>

            <com.google.android.material.button.MaterialButton
                android:id="@+id/add"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:layout_marginStart="4dp"
                android:layout_marginEnd="8dp"
                style="@style/RoutineButtonStyle"
                android:text="ADD"
                app:icon="@drawable/ic_add"/>
        </LinearLayout>
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rv"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@id/ll2"
            android:orientation="vertical"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>
    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>

如果您需要任何其他代码,请告诉我。

【问题讨论】:

  • 你昨天问了这个问题。又不行了。可能会改进您对错误的解释。 “Set”和“kg”是否应该在 cardView 内?描述哪些元素是错误的。在您的图像上带有箭头。只有主要元素和一段代码,没有人可以帮助你。如果增加,我相信我可以为您提供解决方案
  • 对不起。昨天的帖子被删除了,因为根本没有任何回应。并且文章略有编辑。
  • 如果我在家,我会尽快为您提供帮助。知道如何解决这个问题。
  • 使用 LayoutInspector 检查视图的边界。此外,您嵌套的 LinearLayouts 是一种浪费 - 您可以直接在 ConstraintLayout 中对齐“TEST”、Div​​ider 和按钮 - 这就是它的重点。
  • 我的回答解决了你的问题吗?

标签: android android-recyclerview android-cardview


【解决方案1】:

这是您添加/删除CardViewActivity

      //Item List if you want to add one or more Items
        private List<MyItem> myItems = new ArrayList<>();


        private Adapter smallCardAdapter;


        private int size;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            RecyclerView recyclerView = findViewById(R.id.rv);

            //Creates a new Object in the Adapter.class
            smallCardAdapter = new Adapter();
            recyclerView.setAdapter(smallCardAdapter);
            CardView cardView = findViewById(R.id.cardView);
            MaterialButton delete = findViewById(R.id.delete);
            MaterialButton add = findViewById(R.id.add);


            //Add onClickListener
            add.setOnClickListener(v -> {
                try {
                size = myItems.size();

                //if the value is 0, a new item is created
                //if you want to delete the card after 0 than you have to change the value to 0
                if(size == 0){
                    //Creates a new Object in the MyItem.class
                    myItems.add(new MyItem("Set","1kg"));
                }else{
                    MyItem myItem = myItems.get(0);


                    //Replace kg with "" to make a Integer
                    String secondString = myItem.getSecondString().replace("kg","");
                    Integer value = Integer.valueOf(secondString);
                    value++;
                    myItem.setSecondString(value+"kg");
                    myItems.set(0,myItem);

                }

                updateAdapter();
            }catch (Exception e){
                Log.w("MainActivity","Add Button OnClickListener");
                e.printStackTrace();
            }
            });


            //Delete onClickListener
            delete.setOnClickListener(v->{

                try {
                    size = myItems.size();
                    //If the value is 0 then canceled to avoid errors
                    if(size == 0){
                        return;
                    }

                    MyItem myItem = myItems.get(0);

                    //Replace kg with "" to make a Integer
                    String secondString = myItem.getSecondString().replace("kg","");
                    Integer value = Integer.valueOf(secondString);

                    //if the value is one or lower
                    if(value <= 1){
                        //The card will deleted after updateAdapter();
                        myItems.clear();
                    }else{
                        value--;
                        myItem.setSecondString(value+"kg");
                        myItems.set(0,myItem);
                    }
                    updateAdapter();
                }catch (Exception e){
                    Log.w("MainActivity","Delete Button OnClickListener");
                    e.printStackTrace();
                }

            });


        }
        private void updateAdapter(){
            try {
                smallCardAdapter.setItems(myItems);
        }catch (Exception e){
                Log.w("MainActivity","updateAdapter");
                e.printStackTrace();
            }

        }

名为MyItem的自定义Item:

public class MyItem {

    String firstString;
    String secondString;

    public MyItem(String firstString,String secondString){
        this.firstString = firstString;
        this.secondString = secondString;
    }
    public String getFirstString() {
        return firstString;
    }

    public void setFirstString(String firstString) {
        this.firstString = firstString;
    }

    public String getSecondString() {
        return secondString;
    }



       public void setSecondString(String secondString) {
            this.secondString = secondString;
        }
    }

Adapter.java 创建一个smallCard

public class Adapter extends RecyclerView.Adapter<Adapter.SmallCardHolder> {



    private List<MyItem> items = new ArrayList<>();

    @NonNull
    @Override
    public SmallCardHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //                                     I created a new smallcard for the CardView
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.smallcard, parent, false);
        SmallCardHolder smallCardHolder = new SmallCardHolder(itemView);
        return smallCardHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull final SmallCardHolder holder, int position) {

        //get the current item of the position
        MyItem myItem = items.get(position);

        String firstString = myItem.getFirstString();
        String secondString = myItem.getSecondString();

        holder.textViewSet.setText(firstString);
        holder.textViewkg.setText(secondString);
    }


    @Override
    public int getItemCount () {
        return items.size();
    }

    public void setItems(List <MyItem> items) {
        this.items = items;
        notifyDataSetChanged();
    }


    class SmallCardHolder extends RecyclerView.ViewHolder {


        //Here are the TextView's of the smallcard (smallcard.xml)
        private TextView textViewSet;
        private TextView textViewkg;

        public SmallCardHolder(@NonNull View itemView) {
            super(itemView);
            textViewSet = itemView.findViewById(R.id.set);
            textViewkg = itemView.findViewById(R.id.kg);

        }
    }
}

Adapter.java 创建一个名为smallcard.xml 的新布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
    <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        <TextView
                android:id="@+id/set"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Set"
                android:layout_centerVertical="true"
                android:textSize="18sp"
                android:layout_marginStart="5dp"
                android:textColor="?attr/colorPrimary"
                android:textStyle="bold"/>

        <TextView
                android:id="@+id/kg"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="kg"
                android:layout_toRightOf="@id/set"
                android:layout_marginLeft="55dp"
                android:layout_centerVertical="true"
                android:textColor="?attr/colorPrimary"
                android:textSize="16sp"
                android:layout_marginRight="10dp"
                android:maxLines="1"/>
    </RelativeLayout>
</RelativeLayout>

在您的XML 中,您必须为CardView 命名。我称它为cardView。这是代码android:id="@+id/cardView"

结果:

您将在代码中以 cmets 的形式找到更多信息。

【讨论】:

  • 首先,根据您的回答,我只使用了xml代码。但是结果是一样的。。有什么问题?
  • 如果您只使用合乎逻辑的 xml。我们在将保留在回收站视图中的项目上添加了“Set”和“kg”。你想在那里吗?还是只在 CardView 上?它应该只出现一次,还是你会多次使用这些值?
  • 对不起,我忘了说一件事。创建CardView item 时,带有kgset 的子项必须先有一个。正如OP提到的,CardView也是recyclerview的一个项目。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-16
  • 1970-01-01
  • 2019-01-25
  • 2016-11-13
  • 1970-01-01
  • 1970-01-01
  • 2020-07-05
相关资源
最近更新 更多