How to rotate layout orientation between portrait & landscape on touch listener in Android App?

Опубликовано: 27 Апрель 2024
на канале: Programmer World
113
3

In this video it shows the code to detect any kind of rotation movement on touch screen. And then it rotates the Android App layout respectively to Portrait and Landscape orientation.

I hope you like this video. For any questions, suggestions or appreciation please contact us at: https://programmerworld.co/contact/ or email at: [email protected] / [email protected]

Complete source code and other details/ steps of this video are posted in the below link:
https://programmerworld.co/android/ho...


However, the main Java code is copied below also for reference:

package com.programmerworld.rotatethescreen;

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.MotionEvent;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {
private float previousX, previousY;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) - {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
}

@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
if (event.getAction() == MotionEvent.ACTION_MOVE) {
float dx = Math.abs(x - previousX);
float dy = Math.abs(y - previousY);

if (dx GREATER 10 && dy GREATER 10) {
if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
}
previousX = x;
previousY = y;
return true;
}
}




--


Смотрите видео How to rotate layout orientation between portrait & landscape on touch listener in Android App? онлайн без регистрации, длительностью часов минут секунд в хорошем качестве. Это видео добавил пользователь Programmer World 27 Апрель 2024, не забудьте поделиться им ссылкой с друзьями и знакомыми, на нашем сайте его посмотрели 113 раз и оно понравилось 3 людям.