문제

내 Android 애플리케이션에서 장치를 회전하면(키보드를 바깥으로 밀어서) Activity 다시 시작됩니다(onCreate )이라고 합니다.아마도 이것이 예상되는 방식일 것입니다. 그러나 저는 Windows에서 많은 초기 설정을 수행합니다. onCreate 메서드이므로 다음 중 하나가 필요합니다.

  1. 모든 초기 설정을 다른 기능에 넣어 기기 회전 시 모든 설정이 손실되지 않도록 하세요.
  2. 그렇게 만들어 onCreate 다시 호출되지 않고 레이아웃이 조정되거나
  3. 앱을 세로로만 제한하여 onCreate 호출되지 않습니다.
도움이 되었습니까?

해결책

애플리케이션 클래스 사용

초기화에서 수행 중인 작업에 따라 확장되는 새 클래스 생성을 고려할 수 있습니다. Application 초기화 코드를 재정의된 코드로 이동합니다. onCreate 해당 클래스 내의 메소드.

public class MyApplicationClass extends Application {
  @Override
  public void onCreate() {
    super.onCreate();
    // TODO Put your application initialization code here.
  }
}

그만큼 onCreate 애플리케이션 클래스의 는 전체 애플리케이션이 생성될 때만 호출되므로 방향에 따라 활동이 다시 시작되거나 키보드 가시성이 변경되면 트리거되지 않습니다.

이 클래스의 인스턴스를 싱글톤으로 노출하고 getter 및 setter를 사용하여 초기화하는 애플리케이션 변수를 노출하는 것이 좋습니다.

메모:등록하고 사용하려면 매니페스트에 새 애플리케이션 클래스의 이름을 지정해야 합니다.

<application
    android:name="com.you.yourapp.MyApplicationClass"

구성 변경에 대응 [업데이트:이는 API 13부터 더 이상 사용되지 않습니다. 권장 대안 보기]

추가적인 대안으로 방향 및 키보드 가시성 변경과 같이 다시 시작을 유발하는 이벤트를 애플리케이션이 수신하고 활동 내에서 처리하도록 할 수 있습니다.

다음을 추가하여 시작하세요. android:configChanges 활동의 매니페스트 노드에 대한 노드

 <activity android:name=".MyActivity"
      android:configChanges="orientation|keyboardHidden"
      android:label="@string/app_name">

또는 Android 3.2(API 레벨 13) 이상:

<activity android:name=".MyActivity"
      android:configChanges="keyboardHidden|orientation|screenSize"
      android:label="@string/app_name">

그런 다음 활동 내에서 onConfigurationChanged 메소드 및 호출 setContentView GUI 레이아웃을 새로운 방향으로 강제로 다시 수행합니다.

@Override
public void onConfigurationChanged(Configuration newConfig) {
  super.onConfigurationChanged(newConfig);
  setContentView(R.layout.myLayout);
}

다른 팁

Android 3.2 이상의 업데이트 :

주의: Android 3.2 (API 레벨 13)부터 시작하여 "화면 크기"도 변경됩니다 장치가 초상화와 조경 방향 사이를 전환 할 때. 따라서 API 레벨 13 이상을 개발할 때 방향 변경으로 인해 런타임 재시작을 방지하려면 (MinsdKversion 및 TargetSDKversion 속성에 의해 선언 된대로) "screenSize" 값 외에 가치 "orientation" 값. 즉, 당신은 선언해야합니다 android:configChanges="orientation|screenSize". 그러나 애플리케이션이 API 레벨 12 이하를 대상으로하면 활동이 항상이 구성 변경 자체를 처리합니다 (이 구성 변경은 Android 3.2 이상에서 실행될 때에도 활동을 다시 시작하지 않습니다).

중지하려고하는 대신 onCreate() 완전히 해고 된 것에서, 아마도 확인해보십시오 Bundle savedInstanceState 이벤트에 전달되어 그것이 무효인지 아닌지 확인합니다.

예를 들어, 내가 할 때 실행 해야하는 논리가있는 경우 Activity 모든 방향 변화가 아니라 진정으로 만들어졌으며, 그 논리 만 실행합니다. onCreate()savedInstanceState NULL입니다.

그렇지 않으면, 나는 여전히 방향을 위해 레이아웃이 올바르게 다시 그리기를 원합니다.

public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_game_list);

        if(savedInstanceState == null){
            setupCloudMessaging();
        }
}

이것이 궁극적 인 대답인지 확실하지 않지만 그것은 나에게 효과적입니다.

제가 한...

매니페스트에서 활동 섹션에 다음과 같이 덧붙였습니다.

android:configChanges="keyboardHidden|orientation"

활동 코드에서 구현 :

//used in onCreate() and onConfigurationChanged() to set up the UI elements
public void InitializeUI()
{
    //get views from ID's
    this.textViewHeaderMainMessage = (TextView) this.findViewById(R.id.TextViewHeaderMainMessage);

    //etc... hook up click listeners, whatever you need from the Views
}

//Called when the activity is first created.
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    InitializeUI();
}

//this is called when the screen rotates.
// (onCreate is no longer called when screen rotates due to manifest, see: android:configChanges)
@Override
public void onConfigurationChanged(Configuration newConfig)
{
    super.onConfigurationChanged(newConfig);
    setContentView(R.layout.main);

    InitializeUI();
}

설명하는 내용은 기본 동작입니다.다음을 추가하여 이러한 이벤트를 직접 감지하고 처리해야 합니다.

android:configChanges

매니페스트에 추가한 다음 처리하려는 변경 사항을 추가합니다.따라서 오리엔테이션을 위해 다음을 사용합니다.

android:configChanges="orientation"

키보드를 열거 나 닫으려면 다음을 사용하십시오.

android:configChanges="keyboardHidden"

둘 다 처리하려면 다음과 같은 파이프 명령을 사용하여 분리하면 됩니다.

android:configChanges="keyboardHidden|orientation"

이렇게 하면 호출하는 모든 활동에서 onConfigurationChanged 메서드가 트리거됩니다.메서드를 재정의하면 새 값을 전달할 수 있습니다.

도움이 되었기를 바랍니다.

방금이 지식을 발견했습니다.

오리엔테이션 변경을 통해 활동을 생생하게 유지하고 처리합니다. onConfigurationChanged, 문서 그리고 위의 코드 샘플 매니페스트 파일에서 이것을 제안하십시오.

<activity android:name=".MyActivity"
      android:configChanges="orientation|keyboardHidden"
      android:label="@string/app_name">

항상 작동하는 추가 혜택이 있습니다.

보너스 지식은 그것을 생략하는 것입니다 keyboardHidden 논리적으로 보일 수 있지만 에뮬레이터에서 실패를 유발합니다 (최소한 Android 2.1의 경우) : orientation 에뮬레이터가 둘 다 호출하게됩니다 OnCreate 그리고 onConfigurationChanged 때때로, 그리고 단지 OnCreate 다른 시간.

장치에서 실패를 보지 못했지만 다른 사람들에게는 에뮬레이터가 실패하는 것에 대해 들었습니다. 그래서 문서화 할 가치가 있습니다.

방향 변경에서 Android 플랫폼의 데이터를 지속하는 방법을 사용하는 것을 고려할 수도 있습니다. onRetainNonConfigurationInstance() 그리고 getLastNonConfigurationInstance().

이를 통해 서버 페치에서 얻은 정보 또는 계산 된 다른 정보와 같은 구성 변경에서 데이터를 지속 할 수 있습니다. onCreate 또는 Android가 귀하의 Activity 현재 사용중인 방향에 XML 파일을 사용합니다.

보다 여기 또는 여기.

이러한 방법은 이제 모든 사람이 전환하는 권장 사항을 통해 이제 더 이상 사용되지 않음 (위의 솔루션의 대부분의 솔루션에서 알 수 있듯이 오리엔테이션을 처리하는 것보다 여전히 더 유연하지만). Fragments 대신 사용합니다 setRetainInstance(true) 각각에 Fragment 당신은 유지하고 싶습니다.

접근 방식은 유용하지만 조각을 사용할 때 불완전합니다.

조각은 일반적으로 구성 변경에 따라 재현됩니다. 이런 일이 일어나기를 원하지 않으면 사용하십시오

setRetainInstance(true); 조각의 생성자에서

이로 인해 구성 변경 중에 조각이 유지됩니다.

http://developer.android.com/reference/android/app/fragment.html#setretaininstance(boolean)

나는 단순히 추가했다

     android:configChanges="keyboard|keyboardHidden|orientation"

매니페스트 파일에서 추가하지 않았습니다 어느 onConfigurationChanged 내 활동의 방법.

그래서 키보드가 미끄러거나 아무것도 일어나지 않을 때마다.

그만큼 onCreate 당신이 변경할 때에도 메소드가 여전히 호출됩니다 orientation 안드로이드의. 따라서 모든 무거운 기능을이 방법으로 옮기는 것은 도움이되지 않습니다.

매우 간단합니다. 다음 단계를 수행하십시오.

<activity
    android:name=".Test"
    android:configChanges="orientation|screenSize"
    android:screenOrientation="landscape" >
</activity>

이것은 나를 위해 작동합니다 :

메모: 오리엔테이션은 귀하의 요청에 따라 다릅니다

아래 코드를 아래에 넣으십시오 <activity> 태그를 입력하십시오 Manifest.xml:

android:configChanges="screenLayout|screenSize|orientation"
 onConfigurationChanged is called when the screen rotates. 
 (onCreate is no longer called when screen rotates due to manifest, see:  
 android:configChanges)

매니페스트의 일부는 "전화하지 마십시오 onCreate()"?

또한 Google의 문서는 사용을 피한다고 말합니다 android:configChanges (최후의 수단을 제외하고) ....하지만 대체 방법은 모두 제안합니다. ~하다 사용 android:configChanges.

에뮬레이터가 항상 전화 한 것은 내 경험이었습니다. onCreate() 회전시.
그러나 내가 동일한 코드를 실행하는 1-2 장치는 ...하지 마십시오. (왜 차이가 있는지 잘 모르겠습니다.)

이 줄을 매니페스트에 추가하십시오 :-

android:configChanges="orientation|keyboard|keyboardHidden|screenSize|screenLayout|uiMode"

그리고이 스 니펫은 활동에 :-

@Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

안드로이드 매니페스트에서 이루어질 변경은 다음과 같습니다.

android:configChanges="keyboardHidden|orientation" 

내부 활동은 다음과 같습니다.

public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
}

이를 수행하는 방법에는 여러 가지가 있습니다.

활동 상태를 저장하십시오

활동 상태를 저장할 수 있습니다 onSaveInstanceState.

@Override
public void onSaveInstanceState(Bundle outState) {
    /*Save your data to be restored here
    Example : outState.putLong("time_state", time); , time is a long variable*/
    super.onSaveInstanceState(outState);
}

그런 다음 사용하십시오 bundle 상태를 복원합니다.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(savedInstanceState!= null){
       /*When rotation occurs
        Example : time = savedInstanceState.getLong("time_state", 0); */
    } else {
      //When onCreate is called for the first time
    }
}

직접 오리엔테이션 변경을 처리합니다

또 다른 대안은 오리엔테이션 변경을 스스로 처리하는 것입니다. 그러나 이것은 좋은 관행으로 간주되지 않습니다.

매니페스트 파일에 이것을 추가하십시오.

android:configChanges="keyboardHidden|orientation"

Android 3.2 이상 :

android:configChanges="keyboardHidden|orientation|screenSize"

@Override
public void onConfigurationChanged(Configuration config) {
    super.onConfigurationChanged(config);

if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
        //Handle rotation from landscape to portarit mode here
    } else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
        //Handle rotation from portrait to landscape mode here
    }
}

회전을 제한하십시오

회전을 피하기 위해 활동을 초상화 또는 조경 모드로 제한 할 수도 있습니다.

매니페스트 파일의 활동 태그에 이것을 추가하십시오.

        android:screenOrientation="portrait"

또는 귀하의 활동 에서이 프로그래밍 방식으로 구현하십시오.

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

내가 이것을하는 방식은 사용하는 것입니다. onRestoreInstanceState 그리고 onSaveInstanceState 무언가를 저장하는 이벤트 Bundle (저장된 변수가 필요하지 않더라도 거기에 무언가를 넣으십시오. Bundle 비어 있지 않음). 그런 다음, onCreate 방법, Bundle 비어 있고 그것이 있다면 초기화를 수행하지 않으면 그렇게하십시오.

"Android Way"는 아니지만 방향을 처리하고 변경된 방향을 고려하여 위젯을 간단히 재배치함으로써 매우 좋은 결과를 얻었습니다. 당신의 견해를 저장하고 복원 할 필요가 없기 때문에 이것은 다른 어떤 접근법보다 빠릅니다. 또한 호텔 위젯은 정확히 동일한 위젯, 방금 이동 및/또는 크기가 있기 때문에 사용자에게 더 완벽한 경험을 제공합니다. 모델 상태뿐만 아니라 상태도 이런 식으로 보존 될 수 있습니다.

RelativeLayout 때로는 때때로 스스로를 방향으로 바꾸어야하는 견해에 좋은 선택이 될 수 있습니다. 각 어린이 위젯마다 각각에 대해 서로 다른 상대 위치 지정 규칙을 가진 초상화 레이아웃 매개 변수 세트와 조경 레이아웃 매개 변수 세트를 제공합니다. 그럼, 당신의 onConfigurationChanged() 방법, 적절한 것을 전달합니다 setLayoutParams() 각 어린이에게 전화하십시오. 아동 통제 자체가 필요한 경우 내부적 재 혁신적으로, 당신은 그 아이의 방법을 호출하여 재배 향을 수행합니다. 그 아이는 마찬가지로 어떤 방법에도 방법을 부릅니다 그것의 내부 방향 향이 필요한 아동 통제.

화면이 회전 할 때마다 열린 활동이 완료되고 oncreate ()가 다시 호출됩니다.

1 . 화면이 회전 할 때 활동 상태를 저장할 수 있도록 활동 상태를 저장하여 활동의 oncreate ()가 다시 호출 될 때 모든 오래된 물건을 복구 할 수 있습니다. 나타내다 이것 링크

2. 활동의 재시작을 방지하려면 Manifest.xml 파일에 다음 줄을 배치하십시오.

  <activity android:name=".Youractivity"
  android:configChanges="orientation|screenSize"/>

메모: 미래의 누군가가 나와 같은 문제에 직면한다면이 답변을 게시합니다. 나에게 다음 줄은 충분하지 않았습니다.

android:configChanges="orientation"

화면을 회전 시켰을 때`onconfigurationChanged (configuration newConfig) 메소드가 호출되지 않았습니다.

해결책: 또한 문제가 오리엔테이션과 관련이 있어도 "스크린 크기"를 추가해야했습니다. 따라서 AndroidManifest.xml- 파일에서 다음을 추가하십시오.

android:configChanges="keyboardHidden|orientation|screenSize"

그런 다음 방법을 구현하십시오 onConfigurationChanged(Configuration newConfig)

모든 값을 매개 변수에 저장하려면 onsavedinstancestate 메소드를 사용해야합니다.

@Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        outPersistentState.putBoolean("key",value);
    }

그리고 사용

@Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        savedInstanceState.getBoolean("key");
    } 

객체를보기 위해 값을 검색하고 설정하려면 화면 회전이 처리됩니다.

의 활동 섹션에서 manifest, 추가하다:

android:configChanges="keyboardHidden|orientation"

매니페스트 에이 줄을 추가하십시오. android:configChanges="orientation|screenSize"

사람들은 당신이 사용해야한다고 말합니다

android:configChanges="keyboardHidden|orientation"

그러나 Android에서 회전을 처리하는 가장 전문적이고 가장 전문적인 방법은 로더 클래스를 사용하는 것입니다. 유명한 수업은 아니지만 (이유는 모르겠지만) 비동기식보다 훨씬 낫습니다. 자세한 내용은 Udacity의 Android 코스에서 찾은 Android 튜토리얼을 읽을 수 있습니다.

물론, 다른 방법으로, 당신은 값이나보기를 onsaveinstancestate와 함께 저장하고 onrestoreinstancestate와 함께 읽을 수 있습니다. 정말 당신에게 달려 있습니다.

시행 착오가 잠시 후, 나는 대부분의 상황에서 내 요구에 맞는 솔루션을 찾았습니다. 코드는 다음과 같습니다.

매니페스트 구성 :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.pepperonas.myapplication">

    <application
        android:name=".App"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:configChanges="orientation|keyboardHidden|screenSize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

주요 활동:

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity";

    private Fragment mFragment;

    private int mSelected = -1;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate  " + "");

        // null check not realy needed - but just in case...
        if (savedInstanceState == null) {

            initUi();

            // get an instance of FragmentTransaction from your Activity
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

            /*IMPORTANT: Do the INITIAL(!) transaction only once!
            * If we call this everytime the layout changes orientation,
            * we will end with a messy, half-working UI.
            * */
            mFragment = FragmentOne.newInstance(mSelected = 0);
            fragmentTransaction.add(R.id.frame, mFragment);
            fragmentTransaction.commit();
        }
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Log.d(TAG, "onConfigurationChanged  " +
                   (newConfig.orientation
                    == Configuration.ORIENTATION_LANDSCAPE
                    ? "landscape" : "portrait"));

        initUi();

        Log.i(TAG, "onConfigurationChanged - last selected: " + mSelected);
        makeFragmentTransaction(mSelected);
    }


    /**
     * Called from {@link #onCreate} and {@link #onConfigurationChanged}
     */
    private void initUi() {
        setContentView(R.layout.activity_main);
        Log.d(TAG, "onCreate  instanceState == null / reinitializing..." + "");
        Button btnFragmentOne = (Button) findViewById(R.id.btn_fragment_one);
        Button btnFragmentTwo = (Button) findViewById(R.id.btn_fragment_two);
        btnFragmentOne.setOnClickListener(this);
        btnFragmentTwo.setOnClickListener(this);
    }


    /**
     * Not invoked (just for testing)...
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.d(TAG, "onSaveInstanceState  " + "YOU WON'T SEE ME!!!");
    }


    /**
     * Not invoked (just for testing)...
     */
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        Log.d(TAG, "onSaveInstanceState  " + "YOU WON'T SEE ME, AS WELL!!!");
    }


    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume  " + "");
    }


    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause  " + "");
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy  " + "");
    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.btn_fragment_one:
                Log.d(TAG, "onClick btn_fragment_one " + "");
                makeFragmentTransaction(0);
                break;

            case R.id.btn_fragment_two:
                Log.d(TAG, "onClick btn_fragment_two " + "");
                makeFragmentTransaction(1);
                break;

            default:
                Log.d(TAG, "onClick  null - wtf?!" + "");
        }
    }


    /**
     * We replace the current Fragment with the selected one.
     * Note: It's called from {@link #onConfigurationChanged} as well.
     */
    private void makeFragmentTransaction(int selection) {

        switch (selection) {
            case 0:
                mFragment = FragmentOne.newInstance(mSelected = 0);
                break;
            case 1:
                mFragment = FragmentTwo.newInstance(mSelected = 1);
                break;
        }

        // Create new transaction
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack
        transaction.replace(R.id.frame, mFragment);

        /*This would add the Fragment to the backstack...
        * But right now we comment it out.*/
        //        transaction.addToBackStack(null);

        // Commit the transaction
        transaction.commit();
    }

}

및 샘플 조각 :

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * @author Martin Pfeffer (pepperonas)
 */
public class FragmentOne extends Fragment {

    private static final String TAG = "FragmentOne";


    public static Fragment newInstance(int i) {
        Fragment fragment = new FragmentOne();
        Bundle args = new Bundle();
        args.putInt("the_id", i);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView  " + "");
        return inflater.inflate(R.layout.fragment_one, container, false);
    }

}

찾을 수 있습니다 github.

사용 orientation 리스너는 다른 방향으로 다른 작업을 수행합니다.

@Override
public void onConfigurationChanged(Configuration myConfig) 
{
    super.onConfigurationChanged(myConfig);
    int orient = getResources().getConfiguration().orientation; 
    switch(orient) 
    {
       case Configuration.ORIENTATION_LANDSCAPE:
          setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    break;
       case Configuration.ORIENTATION_PORTRAIT:
          setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    break;
       default:
          setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
    }
}

아래 코드를 귀하의 코드에 넣으십시오 Activity 안에 Android Manifest.

android:configChanges="orientation"

오리엔테이션을 변경할 때 활동을 다시 시작하지 않습니다.

화면 방향 (풍경 또는 초상화)을 수정하십시오. AndroidManifest.xml

android:screenOrientation="portrait" 또는 android:screenOrientation="landscape"

이것을 위해 onResume() 메소드가 호출되지 않습니다.

Google에서 도입하는 Android Architechure의 최고의 구성 요소 중 하나는 ViewModel이라는 모든 요구 사항을 충족시킬 것입니다.

Lifecycle Way에 UI 관련 데이터를 저장 및 관리하도록 설계된 스크린 회전에 따라 데이터가 생존 할 수 있도록 설계되었습니다.

class MyViewModel : ViewModel() {

이것을 참조하십시오 :https://developer.android.com/topic/libraries/architecture/viewmodel

이 코드를 사용하여 현재 화면 방향으로 잠글 수 있습니다 ...

int currentOrientation =context.getResources().getConfiguration().orientation;
        if (currentOrientation == Configuration.ORIENTATION_PORTRAIT) {
            ((Activity) context).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            ((Activity) context). setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top