안드로이드 앱 실행시 폰의 가로/세로 상태 즉, 오리엔테이션 (orientation) 에 따라 다른 레이아웃으로 보여주는 액티비티를 작성해야 할 필요가 있을때가 있습니다.
현재 오리엔테이션을 체크하면 되는데, 이는
getResources().gerConfiguration().orientation 값을 보면 확인 가능합니다.
해당 값이
Configuration.ORIENTATION_PORTRAIT 인지,
Configuration.ORIENTATION_LANDSCAPE 인지 확인하여
setContentView() 를 분기하면 됩니다.
안드로이드 폰의 오리엔테이션이 바뀌면 액티비티의 라이프 사이클에 따라, 다시 onCreate() 가 호출되므로, onCreate() 에 위 코드를 넣으면 되겠습니다.
간단한 예제를 보여드리겠습니다.
우선 두개의 레이아웃이 필요합니다. (portrait, landscape)
[activity_portrait.xml]
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="30dp" android:text="Portrait 레이아웃" /> </RelativeLayout>
[activity_landscape.xml]
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="30dp" android:text="Landscape 레이아웃" /> </RelativeLayout>
[MainActivity.java]
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // orientation 에 따라 레이아웃 xml 동적으로 적용. if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { setContentView(R.layout.activity_portrait); } else { setContentView(R.layout.activity_landscape); } // end if } }
[실행화면]
폰을 회전시켜 오리엔테이션을 변경시켜보세요.
출처: http://bitsoul.tistory.com/171 [Happy Programmer~]
댓글 0
번호 | 제목 | 글쓴이 | 날짜 | 조회 수 |
---|---|---|---|---|
공지 | 이 게시판의 게시물들은 테스트 되지 않았음 | 황제낙엽 | 2019.08.28 | 445 |
5 | 안드로이드 API서버(API Server) | 황제낙엽 | 2019.03.24 | 862 |
» |
화면회전(Orientation)에 따른 화면구성하기(레이아웃 분리) [2]
![]() | 황제낙엽 | 2018.12.05 | 73 |
3 | 화면회전(Orientation)에 따른 화면구성하기(레이아웃 분리) [1] | 황제낙엽 | 2018.12.05 | 76 |
2 | 공공데이터 JSON 파싱하기 (HttpURLConnection, JSON) | 황제낙엽 | 2018.10.25 | 1491 |
1 | HttpURLConnection 을 이용하여 JSON데이터 읽어오는 샘플 | 황제낙엽 | 2018.10.25 | 144 |