안드로이드에서 기기의 방향이 변경되었을 때 실행되는 콜백 메소드 사용 예
AndroidManifest.xml 파일에서 activity 엘리먼트의 configChanges='orientation'속성을 이용하면 기기의 방향이 변경되었을 때 Activity 클래스의 멤버 메소드인 onConfigurationChanged()를 실행할 수 있다
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.androidapp" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:configChanges="orientation" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
res/layout/main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/rootLayout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Button" /> <Button android:id="@+id/button2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Button" /> </LinearLayout>
res/layout/landscape.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/rootLayout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Button" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Button" /> </LinearLayout>
MainActivity.java
package com.example.androidapp; import android.os.Bundle; import android.app.Activity; import android.content.res.Configuration; import android.util.Log; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Log.i("onCreate", "onCreate실행됨"); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); int layout = 0; if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){ layout = R.layout.landscape; }else if(newConfig.orientation==Configuration.ORIENTATION_PORTRAIT){ layout = R.layout.main; } setContentView(layout); Log.i("방향전환", newConfig.orientation+""); } }