티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
Activity restart on rotation Android
안드로이드에서 화면 회전 시 액티비티가 다시 시작되는 현상
문제 내용
In my Android application, when I rotate the device (slide out the keyboard) then my Activity
is restarted (onCreate
is called). Now, this is probably how it's supposed to be, but I do a lot of initial setting up in the onCreate
method, so I need either:
제 안드로이드 애플리케이션에서 기기를 회전(키보드를 슬라이드 아웃)하면 내 Activity가 다시 시작됩니다(onCreate가 호출됨). 아마도 이것이 예상되는 동작일 것이지만, onCreate 메소드에서 많은 초기 설정을 수행하므로 다음 중 하나가 필요합니다:
- Put all the initial setting up in another function so it's not all lost on device rotation or
- Make it so
onCreate
is not called again and the layout just adjusts or - Limit the app to just portrait so that
onCreate
is not called.
1. 모든 초기 설정을 onCreate 메서드가 아닌 다른 함수에 넣어서 기기 회전에 모두 손실되지 않도록 합니다.
2. onCreate이 다시 호출되지 않고 레이아웃만 조정되도록 합니다.
3. onCreate가 호출되지 않도록 앱을 세로 모드로만 제한합니다.
높은 점수를 받은 Solution
Using the Application Class
애플리케이션 클래스 사용하기
Depending on what you're doing in your initialization you could consider creating a new class that extends Application
and moving your initialization code into an overridden onCreate
method within that class.
당신이 초기화하는 작업에 따라, Application을 확장하는 새 클래스를 생성하고 해당 클래스 내에서 onCreate 메소드를 재정의하여 초기화 코드를 이동하는 것을 고려할 수 있습니다.
public class MyApplicationClass extends Application {
@Override
public void onCreate() {
super.onCreate();
// TODO Put your application initialization code here.
}
}
The onCreate
in the application class is only called when the entire application is created, so the Activity restarts on orientation or keyboard visibility changes won't trigger it.
애플리케이션 클래스의 onCreate 메소드는 전체 애플리케이션이 생성될 때만 호출되므로, 방향 전환이나 키보드 표시 변경 등의 활동 재시작은 이를 트리거하지 않습니다.
It's good practice to expose the instance of this class as a singleton and exposing the application variables you're initializing using getters and setters.
이 클래스의 인스턴스를 싱글톤으로 노출하고, 초기화하는 애플리케이션 변수를 게터와 세터를 사용하여 노출시키는 것이 좋은 습관입니다.
NOTE: You'll need to specify the name of your new Application class in the manifest for it to be registered and used:
참고: 새로 만든 Application 클래스의 이름을 명시해야만 매니페스트에 등록되고 사용됩니다:
<application
android:name="com.you.yourapp.MyApplicationClass"
Reacting to Configuration Changes [UPDATE: this is deprecated since API 13; see the recommended alternative]
구성 변경에 대응하기 [업데이트: 이 방법은 API 13 이후로 사용이 중지되었습니다. 권장 대안을 참조하십시오.]
As a further alternative, you can have your application listen for events that would cause a restart – like orientation and keyboard visibility changes – and handle them within your Activity.
더 나아가서, 앱이 회전이나 키보드 가시성 변경과 같은 이벤트에 대해 재시작해야 할 때 이벤트를 수신하도록 앱을 구성하고, 해당 이벤트를 Activity 내에서 처리하는 것도 대안이 될 수 있습니다.
Start by adding the android:configChanges
node to your Activity's manifest node
먼저 Activity의 manifest 노드에 android:configChanges 노드를 추가합니다.
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name">
or for Android 3.2 (API level 13) and newer:
또는 안드로이드 3.2 (API 레벨 13) 이상의 경우:
<activity android:name=".MyActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/app_name">
Then within the Activity override the onConfigurationChanged
method and call setContentView
to force the GUI layout to be re-done in the new orientation.
그런 다음, Activity 내에서 onConfigurationChanged 메소드를 오버라이드하고, setContentView를 호출하여 새로운 방향에서 GUI 레이아웃이 다시 수행되도록합니다.
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.myLayout);
}
가장 최근 달린 Solution
One of the best components of android architecture introduced by google will fulfill all the requirements that are ViewModel.
Google에서 소개한 Android 아키텍처 중 가장 좋은 컴포넌트 중 하나는 ViewModel이며, 모든 요구 사항을 충족할 수 있습니다.
That is designed to store and manage UI-related data in a lifecycle way plus that will allow data to survive as the screen rotates
ViewModel은 라이프사이클에 맞게 UI 관련 데이터를 저장하고 관리하며, 화면이 회전해도 데이터를 유지할 수 있도록 설계된 안드로이드 아키텍처의 최고 구성 요소 중 하나입니다.
class MyViewModel : ViewModel() {
Please refer to this: https://developer.android.com/topic/libraries/architecture/viewmodel
다음 링크를 참조해주세요:
출처 : https://stackoverflow.com/questions/456211/activity-restart-on-rotation-android
'개발 > 안드로이드' 카테고리의 다른 글
안드로이드에서 가로 모드 비활성화 방법 (0) | 2022.12.04 |
---|---|
RecyclerView에서 아이템 사이에 디바이더 및 여백 추가하기 (0) | 2022.12.04 |
이메일 전송 인텐트(Chooser에 이메일 관련 앱만 보이게 하기) (0) | 2022.12.03 |
안드로이드 앱에서 chooser 대신 Google Play Store 바로 열기 (0) | 2022.12.03 |
HTML 파일 WebView에 로드하기 (0) | 2022.12.03 |