Потеря стилей при наследовании из группы просмотра карточек материалов

#java #android #material-design #material-components-android #material-components

#java #Android #материал-дизайн #материал-компоненты-android #материал-компоненты

Вопрос:

Я пишу курсовой проект, и мне нужно создать пользовательскую карточку материала. Но когда я наследую материальную карту, стили исчезают. Я перепробовал все решения, которые нашел в Интернете. Я буду благодарен за любую помощь.

MainActivity.java

 public class MainActivity extends AppCompatActivity {

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

    Case aCase = new Case();
    aCase.setId(183928);
    aCase.setStatus("Status");
    aCase.setDescription("fermentum dui faucibus in ornare quam viverra orci sagittis eu");

    CaseView caseView = findViewById(R.id.caseView);
    caseView.setCase(aCase);
}
}
 

activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

<com.google.android.material.card.MaterialCardView
    android:id="@ id/card"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="16dp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/title"
                android:textAppearance="?attr/textAppearanceHeadline6" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:text="secondary_text"
                android:textAppearance="?attr/textAppearanceBody2"
                android:textColor="?android:attr/textColorSecondary" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:text="supporting_text"
                android:textAppearance="?attr/textAppearanceBody2"
                android:textColor="?android:attr/textColorSecondary" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:orientation="horizontal">

            <com.google.android.material.button.MaterialButton
                style="?attr/borderlessButtonStyle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="8dp"
                android:text="action_1" />

            <com.google.android.material.button.MaterialButton
                style="?attr/borderlessButtonStyle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="action_2" />
        </LinearLayout>

    </LinearLayout>

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

<com.barmatograf.interpolith.view.CaseView
    android:id="@ id/caseView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
 

скриншот https://i.stack.imgur.com/htRq0.png

класс модели для пользовательской карты

 package com.barmatograf.interpolith.model;

public class Case {
    private Integer id;
    private String description;
    private String status;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}
 

CaseView.java

 package com.barmatograf.interpolith.view;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

import com.barmatograf.interpolith.R;
import com.barmatograf.interpolith.model.Case;
import com.google.android.material.card.MaterialCardView;

public class CaseView extends MaterialCardView {
private Case aCase;
private TextView number;
private TextView status;
private TextView description;

public CaseView(Context context) {
    this(context, null);
}

public CaseView(Context context, AttributeSet attrs) {
    this(context, attrs, R.attr.materialCardViewStyle);
}

public CaseView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(context);
}

private void init(Context context) {
    inflate(context, R.layout.case_view_layout, this);
    number = findViewById(R.id.case_number);
    status = findViewById(R.id.case_status);
    description = findViewById(R.id.case_description);
}

public void setCase(Case aCase) {
    this.aCase = aCase;
    if (aCase != null) {
        if (aCase.getId() != null)
            number.setText(String.valueOf(aCase.getId()));
        if (aCase.getStatus() != null)
            status.setText(aCase.getStatus());
        if (aCase.getDescription() != null) {
            String descriptionText = aCase.getDescription();
            int length = Math.min(descriptionText.length(), 100);
            descriptionText = descriptionText.substring(0, length);
            descriptionText = descriptionText.trim();
            descriptionText = descriptionText   "...";
            description.setText(descriptionText);
        }
    }
}

public Case getCase() {
    return aCase;
}
}
 

case_view_layout.xml

 <?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    android:orientation="horizontal">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="16dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/title"
            android:textAppearance="?attr/textAppearanceHeadline6" />

        <TextView
            android:id="@ id/case_number"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?attr/textAppearanceHeadline6" />
    </LinearLayout>

    <TextView
        android:id="@ id/case_status"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:textAppearance="?attr/textAppearanceBody2"
        android:textColor="?android:attr/textColorSecondary" />

    <TextView
        android:id="@ id/case_description"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:textAppearance="?attr/textAppearanceBody2"
        android:textColor="?android:attr/textColorSecondary" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
 

стили

 <style name="AppTheme" parent="Theme.MaterialComponents">
    <item name="materialCardViewStyle">@style/Widget.MaterialComponents.CardView</item>
</style>
 

Ответ №1:

обратите внимание, что у вас CaseView ЕСТЬ a MaterialCardView ( extends ) , но у вас есть и другой MaterialCardView в качестве корня вашего раздутого XML. это другой View без набора стилей (без xml style attr), на самом деле ваш CaseView содержит один дочерний элемент — другой MaterialCardView .

имхо, он должен учитывать «глобальную» настройку from AppTheme , но все же стоит исправить этот двойной CardView регистр — используйте <merge tag вместо root MaterialCardView в XML. inflate метод добавит все дочерние элементы, размещенные внутри <merge> тега, в CaseView

Комментарии:

1. Большое вам спасибо! В дополнение к вашему совету мне пришлось перестроить проект, чтобы добиться успеха