স্ক্রিন অরিয়েন্টেশন পরিবর্তন শোনা: onConfigurationChanged
এই টিউটোরিয়ালটি দেখাবে কীভাবে অ্যাক্টিভিটি রি-ক্রিয়েট না করেই পোর্ট্রেইট এবং ল্যান্ডস্কেপ মোডের পরিবর্তন ডিটেক্ট করতে হয়।
পদক্ষেপ ১: প্রজেক্ট তৈরি করুন
Android Studio-তে নতুন প্রজেক্ট তৈরি করুন।
পদক্ষেপ ২: লেআউট XML (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="24sp"
android:textStyle="bold" />
</LinearLayout>
পদক্ষেপ ৩: MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "Landscape Mode", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
Toast.makeText(this, "Portrait Mode", Toast.LENGTH_SHORT).show();
}
}
}
পদক্ষেপ ৪: AndroidManifest.xml - গুরুত্বপূর্ণ কনফিগারেশন
<activity android:name=".MainActivity"
android:configChanges="orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
কেন android:configChanges দরকার?
ডিফল্টভাবে অরিয়েন্টেশন পরিবর্তন হলে অ্যান্ড্রয়েড অ্যাক্টিভিটি ধ্বংস করে পুনরায় তৈরি করে (onCreate কল হয়)। android:configChanges="orientation|screenSize" যোগ করলে অ্যাক্টিভিটি রি-ক্রিয়েট হয় না, বরং onConfigurationChanged() কল হয়।
সতর্কতা ও সেরা অনুশীলন
- ভিউ রি-লেআউট: onConfigurationChanged-এ ম্যানুয়ালি ভিউ আপডেট করতে হতে পারে
- ভিউমডেল ব্যবহার: আধুনিক অ্যাপে ViewModel ব্যবহার করলে ডেটা সংরক্ষণ সহজ
- ConstraintLayout: রেসপন্সিভ লেআউটে অরিয়েন্টেশন হ্যান্ডলিং স্বয়ংক্রিয় হয়
- API 32+: নতুন API-তে windowInsets ব্যবহার করুন আরও নিয়ন্ত্রণের জন্য
বিকল্প: OrientationEventListener
সেন্সর-ভিত্তিক অরিয়েন্টেশন ডিটেকশনের জন্য (UI রোটেশন ছাড়া):
OrientationEventListener orientationListener = new OrientationEventListener(this) {
@Override
public void onOrientationChanged(int orientation) {
// orientation: 0-359 degrees
}
};
orientationListener.enable();