Android Screen Orientation Programmatically (ASOP)

To change screen orientation programmatically using buttons in an Android app, you can follow these steps using Kotlin:

1. Open or create an Android Studio project.
2. Open your activity layout XML file (for example, `activity_main.xml`) and add a button:

<Button

    android:id= "@+id/btnChangeOrientation"

    android:layout_width= "wrap_content"

    android:layout_height= "wrap_content"

    android:text= "Change Orientation"

    android:onClick= "onChangeOrientationClick" />

3. Open the Kotlin file for your activity (for example, `MainActivity.kt`) and add the following code:

import android.content.pm.ActivityInfo

import android.os.Bundle

import android.view.View

import androidx.appcompat.app.AppCompatActivity



class  MainActivity : AppCompatActivity() {



    override  fun  onCreate (savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)

    }



    fun  onChangeOrientationClick (view: View) {

        val currentOrientation = resources.configuration.orientation



        // Change screen orientation based on current orientation

        requestedOrientation = if (currentOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {

            ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE

        } else {

            ActivityInfo.SCREEN_ORIENTATION_PORTRAIT

        }

    }

}

With this, when the “Change Orientation” button is pressed, your app’s screen orientation will change between portrait and landscape. The above code detects the current orientation and changes it to a different orientation. You can customize the logic as per your app’s requirements.

Be sure to customize UI elements and other functions according to your project needs.


Post a Comment

Previous Next

نموذج الاتصال