Как отобразить список содержимого с вертикальной прокруткой в ​​RecyclerView, если используется портретный режим, и список содержимого с горизонтальной прокруткой, если используется альбомный режим? - PullRequest
0 голосов
/ 21 ноября 2019

В моем приложении для Android я использую RecyclerView для отображения списка контента. Но требование заключается в том, что список должен прокручиваться по вертикали, если режим экрана - «Портрет», и по горизонтали, если режим экрана - «Пейзаж». Чтобы добиться этого, я создал альбомную разметку в каталоге «layout-land» в каталоге «main / res». Ниже приведен код xml для каталогов «res / layout» и «res / layout-land» -

" res / layout / activity_media "

<RelativeLayout 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"
                android:background="@color/media_bg_color"
                tools:context=".Activities.MediaActivity">

    <include
            android:id="@+id/tool_bar"
            layout="@layout/media_actionbar_layout"/>

    <TextView
            android:id="@+id/tvAppInfo"
            android:layout_width="match_parent"
            android:textSize="16dp"
            android:gravity="left"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:lineSpacingExtra="2sp"
            android:layout_marginTop="10dp"
            android:textColor="@android:color/white"
            android:text="@string/app_info"
            android:layout_below="@+id/tool_bar"
            android:layout_height="wrap_content"/>

    <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rvMediaList"
            android:layout_width="match_parent"
            android:layout_below="@+id/tvAppInfo"
            android:layout_marginLeft="20dp"
            android:scrollbars="vertical"
            android:layout_marginRight="20dp"
            android:layout_marginTop="20dp"
            android:layout_height="match_parent">

    </androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>

" res / layout-land / activity_media "

<RelativeLayout 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"
                android:background="@color/media_bg_color"
                tools:context=".Activities.MediaActivity">

    <include
            android:id="@+id/tool_bar"
            layout="@layout/media_actionbar_layout"/>

    <LinearLayout
            android:id="@+id/llParent"
            android:layout_width="match_parent"
            android:orientation="horizontal"
            android:weightSum="100"
            android:layout_marginTop="10dp"
            android:layout_below="@+id/tool_bar"
            android:layout_height="match_parent">

        <TextView
                android:id="@+id/tvAppInfo"
                android:layout_width="0dp"
                android:textSize="16dp"
                android:gravity="left"
                android:layout_marginLeft="20dp"
                android:layout_weight="35"
                android:lineSpacingExtra="2sp"
                android:textColor="@android:color/white"
                android:text="@string/app_info"
                android:layout_height="wrap_content"/>

        <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/rvMediaList"
                android:layout_width="0dp"
                android:layout_weight="65"
                android:scrollbars="horizontal"
                android:layout_marginLeft="30dp"
                android:layout_marginRight="20dp"
                android:layout_height="match_parent">

        </androidx.recyclerview.widget.RecyclerView>
    </LinearLayout>
</RelativeLayout>

Ниже я упомянул мою запись "MediaActivity" в файле manifest.xml--

<activity
            android:name=".Activities.MediaActivity"
            android:configChanges="keyboardHidden|orientation|screenSize"
            android:screenOrientation="sensor">
    </activity>

Затем я перезаписываю метод onConfigurationChanged () в своем классе MediaActivity.java, чтобы установить горизонтальное расположение для RecyclerView, если режим экрана имеет альбомную ориентацию и ниже моего кода метода onConfigurationChanged () -

@Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);
        orientationLand = (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE ? true : false);

        if(orientationLand)
        {
            rvMediaList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, true));
        }
    }

Теперь проблема заключается в горизонтальной прокрутке списка RecyclerView, но с учетом только макета «res / layout / activity_media» даже в ландшафтном режиме, а не макета «res / layout-land / activity_media».

1 Ответ

0 голосов
/ 21 ноября 2019

Попробуйте это

 @Override
 public void onConfigurationChanged(Configuration newConfig) {
                        super.onConfigurationChanged(newConfig);
                        // Checks the orientation of the screen
                        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
                            mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
                            madapter = new YourAdapter(this, arrList);
                            mRecyclerView.setAdapter(madapter);
                        } else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){

                            LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,false);
                            mRecyclerView.setLayoutManager(layoutManager);
                            madapter = new YourAdapter(this, arrList);// for your adapter
                            mRecyclerView.setAdapter(madapter);
                        }

Также в файле манифеста включить android: configChanges

 <activity android:name=".YourActivity"
      android:configChanges="orientation|keyboardHidden"
      android:label="@string/app_name">
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...