Как вы динамически добавляете несколько дочерних макетов в MaterialCardView из фрагмента? - PullRequest
0 голосов
/ 10 июля 2019

На одном из моих фрагментов у меня есть CardView, куда я хочу добавить несколько дочерних представлений на основе файла макета.Количество добавляемых дочерних представлений будет зависеть от того, сколько элементов содержится в объекте List (поэтому я использую цикл for для итерации по списку).Когда я добавляю представление к просмотру карты, приложение вылетает с ошибкой, говорящей о необходимости удалить дочерние представления перед добавлением другого представления.

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>
        <import type="com.mahaprasad.mahaprasad.models.DeliveryMethod" />
        <import type="android.view.View" />
        <variable
            name="viewModel"
            type="com.mahaprasad.mahaprasad.screens.checkoutflow.CheckoutSharedViewModel" />
    </data>

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.core.widget.NestedScrollView
            android:id="@+id/nested_scroll_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="50dp">

            <androidx.constraintlayout.widget.ConstraintLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true">

                <com.google.android.material.card.MaterialCardView
                    android:id="@+id/basket_products_card"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="16dp">

                    <!-- Layout Child Views Should go here -->                   

                </com.google.android.material.card.MaterialCardView>

            </androidx.constraintlayout.widget.ConstraintLayout>

        </androidx.core.widget.NestedScrollView>

        <com.google.android.material.button.MaterialButton
            android:id="@+id/checkout_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|start"
            android:insetBottom="0dp"
            android:text="Place Order"
            android:textAlignment="viewStart"
            app:backgroundTint="@color/green_button_colour"
            app:cornerRadius="0dp" />

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

</layout>

Layout template
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable
            name="product"
            type="com.mahaprasad.mahaprasad.models.Product" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp">

        <androidx.appcompat.widget.AppCompatImageView
            android:id="@+id/product_image"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:maxWidth="100dp"
            android:maxHeight="100dp"
            android:src="@drawable/chedvo"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            tools:layout_editor_absoluteX="50dp" />

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/product_name_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="5dp"
            android:layout_marginTop="5dp"
            android:maxWidth="300dp"
            android:textSize="18sp"
            android:textColor="@color/colourBlack"
            android:autoSizeMaxTextSize="18sp"
            android:autoSizeMinTextSize="14sp"
            android:autoSizeStepGranularity="1sp"
            android:autoSizeTextType="uniform"
            android:maxLines="1"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toEndOf="@id/product_image"
            app:layout_constraintBottom_toTopOf="@id/product_size_text"
            app:productName="@{product}"
            app:autoSizeMaxTextSize="18sp"
            app:autoSizeMinTextSize="14sp"
            app:autoSizeStepGranularity="2sp"
            tools:text="Chedvo (Farari Chedvoooooo)"
            tools:targetApi="o" />

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/product_size_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="5dp"
            android:textSize="15sp"
            app:layout_constraintTop_toBottomOf="@id/product_name_text"
            app:layout_constraintStart_toEndOf="@id/product_image"
            app:productSize="@{product}"
            tools:text="6 per pack" />

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/product_price_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="5dp"
            android:textColor="@color/colourBlack"
            android:textSize="15sp"
            app:layout_constraintStart_toEndOf="@id/product_image"
            app:layout_constraintTop_toBottomOf="@id/product_size_text"
            app:layout_constraintBottom_toBottomOf="parent"
            app:productBasketQuantity="@{product}"
            tools:text="1 x £5.00" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

class ReviewOrderFragment : Fragment() {
    private lateinit var viewModel: CheckoutSharedViewModel
    private val args: ReviewOrderFragmentArgs by navArgs()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val binding: FragmentReviewOrderBinding = DataBindingUtil.inflate(
            inflater, R.layout.fragment_review_order, container, false)

        viewModel = activity?.run {
            ViewModelProviders.of(this).get(CheckoutSharedViewModel::class.java)
        } ?: throw Exception("Invalid Activity")

        populateBasketProductsCard(inflater, binding.basketProductsCard)

        binding.viewModel = viewModel
        binding.lifecycleOwner = this

        return binding.root
    }

    private fun populateBasketProductsCard(inflater: LayoutInflater, basketProductsCard: MaterialCardView) {
        val productInfoView: View = inflater.inflate(R.layout.layout_review_order_product_card, null)
        val basket = args.order.basket.basket

        basket.forEachIndexed { index, product ->
            val productsCardBinding: LayoutReviewOrderProductCardBinding = DataBindingUtil.inflate(
                inflater, R.layout.layout_review_order_product_card, null, false)

            productsCardBinding.product = product

            basketProductsCard.addView(
                productInfoView,
                index,
                ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
            )
        }

    }

}

Ответы [ 2 ]

1 голос
/ 11 июля 2019

Просто добавьте LinearLayout внутри MaterialCardView и вставьте ваши дочерние виды непосредственно в макет. MaterialCardView extends CardView и CardView предназначены для хранения одного дочернего представления внутри себя.

<com.google.android.material.card.MaterialCardView
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginTop="16dp">
    <LinearLayout
    android:id="@+id/basket_products_card"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
        <!-- Layout Child Views Should go here -->
    </LinearLayout>
</com.google.android.material.card.MaterialCardView>
0 голосов
/ 10 июля 2019

Почему бы вам не установить макет в качестве дочернего представления CardView и программно добавить элементы списка в этот макет вместо добавления всех их в CardView?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...