У меня есть приложение, которое работает в ландшафтном режиме. У меня есть RecycleView как часть моего основного вида. В горизонтальном режиме, если я прокручиваю жест по вертикали, RecycleView хорошо прокручивается и не прокручивает, когда выполняется жест горизонтальной прокрутки, что должно происходить в обычном режиме. Затем я переключаю свой телефон в портретный режим. В этом случае основной вид остается таким же, как в альбомной ориентации. Мне нужно только чтобы RecyclerView вращался на 90 градусов. После обычного поворота RecyclerView должен прокручиваться, если я делаю жест вертикальной прокрутки. Но в моем случае, RecyclerView прокручивается, даже если я делаю жест горизонтальной прокрутки. Обычно это не должно происходить
Здесь я приведу пример кода проекта ниже,
AndroidManifest. xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.axis.rotaterecyclerview">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:launchMode="singleTop"
android:screenOrientation="landscape">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity. java,
package com.axis.rotaterecyclerview;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.res.Configuration;
import android.os.Bundle;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
ArrayList<String> list = new ArrayList<>();
list.add("DATA 1");
list.add("DATA 2");
list.add("DATA 3");
list.add("DATA 4");
list.add("DATA 5");
list.add("DATA 6");
list.add("DATA 7");
list.add("DATA 8");
list.add("DATA 10");
list.add("DATA 11");
list.add("DATA 12");
RecyclerAdapter recyclerAdapter = new RecyclerAdapter(this, list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(recyclerAdapter);
getDeviceRotation();
}
private void getDeviceRotation() {
SimpleOrientationListener mOrientationListener = new SimpleOrientationListener(
this) {
@Override
public void onSimpleOrientationChanged(int orientation) {
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
recyclerView.setRotation(0);
} else if (orientation == Configuration.ORIENTATION_PORTRAIT) {
recyclerView.setRotation(-90);
}
}
};
mOrientationListener.enable();
}
}
SimpleOrientationListener. java,
package com.axis.rotaterecyclerview;
import android.content.Context;
import android.content.res.Configuration;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.WindowManager;
import java.util.concurrent.locks.ReentrantLock;
public abstract class SimpleOrientationListener extends OrientationEventListener {
public static final int CONFIGURATION_ORIENTATION_UNDEFINED = Configuration.ORIENTATION_UNDEFINED;
private volatile int defaultScreenOrientation = CONFIGURATION_ORIENTATION_UNDEFINED;
public int prevOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
private Context ctx;
private ReentrantLock lock = new ReentrantLock(true);
public SimpleOrientationListener(Context context) {
super(context);
ctx = context;
}
public SimpleOrientationListener(Context context, int rate) {
super(context, rate);
ctx = context;
}
@Override
public void onOrientationChanged(final int orientation) {
int currentOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
if (orientation >= 330 || orientation < 30) {
currentOrientation = Surface.ROTATION_0;
} else if (orientation >= 60 && orientation < 120) {
currentOrientation = Surface.ROTATION_90;
} else if (orientation >= 150 && orientation < 210) {
currentOrientation = Surface.ROTATION_180;
} else if (orientation >= 240 && orientation < 300) {
currentOrientation = Surface.ROTATION_270;
}
if (prevOrientation != currentOrientation && orientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
prevOrientation = currentOrientation;
if (currentOrientation != OrientationEventListener.ORIENTATION_UNKNOWN)
reportOrientationChanged(currentOrientation);
}
}
private void reportOrientationChanged(final int currentOrientation) {
int defaultOrientation = getDeviceDefaultOrientation();
int orthogonalOrientation = defaultOrientation == Configuration.ORIENTATION_LANDSCAPE ? Configuration.ORIENTATION_PORTRAIT
: Configuration.ORIENTATION_LANDSCAPE;
int toReportOrientation;
if (currentOrientation == Surface.ROTATION_0 || currentOrientation == Surface.ROTATION_180)
toReportOrientation = defaultOrientation;
else
toReportOrientation = orthogonalOrientation;
onSimpleOrientationChanged(toReportOrientation);
}
/**
* Must determine what is default device orientation (some tablets can have default landscape). Must be initialized when device orientation is defined.
*
* @return value of {@link Configuration#ORIENTATION_LANDSCAPE} or {@link Configuration#ORIENTATION_PORTRAIT}
*/
private int getDeviceDefaultOrientation() {
if (defaultScreenOrientation == CONFIGURATION_ORIENTATION_UNDEFINED) {
lock.lock();
defaultScreenOrientation = initDeviceDefaultOrientation(ctx);
lock.unlock();
}
return defaultScreenOrientation;
}
/**
* Provides device default orientation
*
* @return value of {@link Configuration#ORIENTATION_LANDSCAPE} or {@link Configuration#ORIENTATION_PORTRAIT}
*/
private int initDeviceDefaultOrientation(Context context) {
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Configuration config = context.getResources().getConfiguration();
int rotation = windowManager.getDefaultDisplay().getRotation();
boolean isLand = config.orientation == Configuration.ORIENTATION_LANDSCAPE;
boolean isDefaultAxis = rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180;
int result = CONFIGURATION_ORIENTATION_UNDEFINED;
if ((isDefaultAxis && isLand) || (!isDefaultAxis && !isLand)) {
result = Configuration.ORIENTATION_LANDSCAPE;
} else {
result = Configuration.ORIENTATION_PORTRAIT;
}
return result;
}
/**
* Fires when orientation changes from landscape to portrait and vice versa.
*
* @param orientation value of {@link Configuration#ORIENTATION_LANDSCAPE} or {@link Configuration#ORIENTATION_PORTRAIT}
*/
public abstract void onSimpleOrientationChanged(int orientation);
}
RecyclerAdapter. java,
package com.axis.rotaterecyclerview;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import androidx.recyclerview.widget.RecyclerView;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private Context mContext;
private LayoutInflater mInflater;
private ArrayList<String> list;
public RecyclerAdapter(Context context, ArrayList<String> list) {
this.mContext = context;
this.list = list;
this.mInflater = LayoutInflater.from(context);
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.rv_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.setIsRecyclable(false);
holder.textView.setText(list.get(holder.getAdapterPosition()));
}
@Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView textView;
ViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text);
}
}
}
activity_main. xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
rv_item. xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="300dp"
android:text="sample"
android:textColor="#000000"
android:textSize="20dp"
android:gravity="center"
android:background="#E2A7A7"
android:layout_margin="10dp"/>
</LinearLayout>
Когда я поворачиваю устройство в портретное положение, RecyclerView также поворачивается на 90 градусов, в то время RecyclerView не прокручивается должным образом, и он прокручивается как вертикально, так и горизонтально. Но приложение работает нормально, когда устройство находится в альбомной ориентации.