Установка высоты CardView как пользовательский процент от размера экрана - PullRequest
0 голосов
/ 01 июня 2019

У меня есть фрагмент, который отображает RecyclerView, который заполнен массивом объектов - 1 CardView для каждого объекта. Я хочу, чтобы мое приложение отображало 5 CardView и выглядело 6-е CardView, смотрящее на экран независимо от размера (устанавливая высоту каждого CardView равной 18% от высоты всего экрана). В настоящее время у меня есть этот код для установки высоты каждого CardView равной 1/6 всего экрана. Проблема этого метода заключается в том, что я могу сделать только высоту каждого CardView 1 / x всего экрана, где x может быть только целым числом (вместо этого я хочу сделать высоту каждого CardView пользовательским процентом от высоты экрана). только сделать его размером 1/3, 1/4, 1/5 и т. д. размера экрана).

DisplayMetrics displayMetrics = new DisplayMetrics();
WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Log.i(TAG, "WM     " + wm);

Point size = new Point();
Display display = wm.getDefaultDisplay();
display.getSize(size);
int heighty = size.y;
int height = heighty/6; // does not work with doubles because setLayoutParams must be (int)

Log.i(TAG, "height     " + heighty + "       " + display);
CardView cm = (CardView)view.findViewById(R.id.card);
Log.i(TAG, "cm     " + cm);
ViewGroup.LayoutParams params = cm.getLayoutParams();

Log.i(TAG, "params      params     " + params);
params.height= height;
params.width=MATCH_PARENT;
cm.setLayoutParams(params);

Это мой xml-файл для каждого отображаемого CardView

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.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:cardElevation="4dp"
android:id="@+id/card"
app:cardUseCompatPadding="true">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:weightSum="3"
    android:orientation="vertical">

    <TextView
        android:id="@+id/user_name_iv"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        android:paddingStart="10dp"
        android:paddingEnd="0dp"
        android:textColor="#000000"
        android:textSize="12sp"
        android:layout_weight="0.7"
        />

    <TextView
        android:id="@+id/user_desc"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        android:paddingStart="10dp"
        android:paddingEnd="0dp"
        android:textColor="#000000"
        android:textSize="12sp"
        android:paddingRight="5dp"
        android:paddingLeft="5dp"
        android:layout_weight="0.7"
        />

    <ImageView
        android:id="@+id/user_iv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="10dp"
        android:paddingRight="5dp"
        android:paddingLeft="5dp"
        android:contentDescription="@string/image"
        android:layout_weight="1.5"/>


</LinearLayout>

Я попытался изменить эту реализацию, чтобы использовать LinearLayout внутри ConstraintLayout, где высота LinearLayout составляет 18% от всего экрана, а высота экземпляров LinearLayout (ImageView и 2 textView) - это процент от LinearLayout. Мой XML для этой реализации:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:id="@+id/cardview_id"
    android:orientation="vertical"
    app:layout_constraintHeight_default="percent"
    app:layout_constraintHeight_percent="0.18"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:weightSum="1">

<TextView
    android:id="@+id/user_name_iv"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="0.2"
    android:layout_marginBottom="0dp"
    android:layout_marginTop="10dp"
    android:paddingStart="10dp"
    android:paddingEnd="0dp"
    android:textColor="#000000"
    android:textSize="24sp"
    />
<TextView
    android:id="@+id/user_desc"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="0.2"
    android:layout_marginBottom="10dp"
    android:layout_marginTop="5dp"
    android:paddingStart="10dp"
    android:paddingEnd="0dp"
    android:textColor="#000000"
    android:textSize="14sp"
    android:layout_below="@id/user_name_iv"
    android:paddingRight="5dp"
    android:paddingLeft="5dp"
    />

<ImageView
    android:scaleType="centerCrop"
    android:id="@+id/user_iv"
    android:layout_height="0dp"
    android:layout_weight="0.6"
    android:layout_width="match_parent"
    android:paddingRight="5dp"
    android:paddingLeft="5dp"/>

</LinearLayout>
</android.support.constraint.ConstraintLayout>

Это делает каждый экземпляр RecyclerView необходимой мне высотой (18% от высоты экрана), но мой RecyclerView делает каждый отдельный экземпляр назначенным одному экрану вместо отображения экземпляров прямо под другим (я знаю, что это потому что высота ConstraintLayout равна match_parent, но wrap_content заставляет содержимое исчезать). Я хотел бы знать, существует ли идеальный подход к выполнению того, что я пытаюсь сделать, или к решению вышеуказанной проблемы.

Мой RecyclerView xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:id="@+id/nestedView"
android:fillViewport="true"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</android.support.v4.widget.NestedScrollView>

Любая помощь будет очень признательна, спасибо.

1 Ответ

0 голосов
/ 02 июня 2019

Я нашел решение. Для тех, кто имеет эту проблему и хотел бы получить ответ, я изменил приведенный выше код Java, чтобы высота каждого cardView была любой долей высоты экрана.

        DisplayMetrics displayMetrics = new DisplayMetrics();
        WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
        Log.i(TAG, "WM     " + wm);

        Point size = new Point();
        Display display = wm.getDefaultDisplay();
        display.getSize(size);
        int heighty = size.y;
        double heightDouble = heighty/2.5; // this will make the screen display 2 cardview's and have half of the third one peeking. replace 2.5 with any decimal you desire to make your last cardview peek a certain amount
        int height = (int) Math.rint(heightDouble); 



        Log.i(TAG, "height     " + heighty + "       " + display);
        CardView cm = (CardView)view.findViewById(R.id.card);
        Log.i(TAG, "cm     " + cm);
        ViewGroup.LayoutParams params = cm.getLayoutParams();

        Log.i(TAG, "params      params     " + params);
        params.height= height;
        params.width=MATCH_PARENT;
        cm.setLayoutParams(params);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...