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

Published: 27 April 2024
on channel: 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;
}
}




--


Watch video How to rotate layout orientation between portrait & landscape on touch listener in Android App? online without registration, duration hours minute second in high quality. This video was added by user Programmer World 27 April 2024, don't forget to share it with your friends and acquaintances, it has been viewed on our site 113 once and liked it 3 people.