IT TIP

ActionBar 위쪽 탐색은 onResume 대신 부모 활동을 다시 만듭니다.

itqueen 2020. 11. 3. 19:34
반응형

ActionBar 위쪽 탐색은 onResume 대신 부모 활동을 다시 만듭니다.


Up Navigation에 권장되는 접근 방식을 사용하고 있으며 코드는 다음과 같습니다.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            Intent h = new Intent(ShowDetailsActivity.this, MainActivity.class);
            h.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(h);
            return true;
        default: return super.onOptionsItemSelected(item);
    }
}

사용 사례는 다음과 같습니다.

  1. "MainActivity"앱을 실행합니다.
  2. 버튼을 클릭하여 "ShowDetailsActivity"로 이동합니다.
  3. UP ActionBar 탐색을 클릭합니다.

문제는 내가 UP을 클릭 한 후, MainActivity가 다시 onCreate () 메서드에 도달하고 ShowDetailsActivity에서 "finish ()"를 호출 한 것처럼 일반적인 onResume ()에서 시작하는 대신 모든 상태를 잃는 것입니다. 왜? 이것이 항상 작동하는 방식이며 Android가 "위로"탐색 접근 방식을 사용하여 탐색되는 모든 활동을 다시 만드는 데 예상되는 동작입니까? 뒤로 버튼을 누르면 예상되는 onResume 수명주기가 표시됩니다.

Android "적절한"것이 존재하지 않는 경우 이것이 내 솔루션입니다.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            Intent upIntent = new Intent(this, MainActivity.class);
            if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
                NavUtils.navigateUpTo(this, upIntent);
                finish();
            } else {
                finish();
            }
            return true;
        default: return super.onOptionsItemSelected(item);
    }
}

매니페스트 파일의 상위 활동에 다음을 추가합니다.

android:launchMode="singleTop"

답변 에 관하여


그 이유는 ,이에 대한 그 안드로이드 용도 표준 발사 모드, 당신은 다른 모드를 지정하지 않은 경우 네비게이션을 사용하는 경우, 활동이 재현된다. 그것의 의미는

"시스템은 항상 대상 작업에서 활동의 새 인스턴스를 만듭니다."

따라서 활동이 다시 생성됩니다 ( 여기에서 문서 참조 ).

해결책 은 MainActivity의 시작 모드를 다음과 같이 선언하는 것입니다.

android:launchMode="singleTop"

에서 AndroidManifest.xml
(항상 함께 작동합니다 Intent.FLAG_ACTIVITY_CLEAR_TOP)

또는 인FLAG_ACTIVITY_SINGLE_TOP 텐트 플래그에 추가 하여 활동에 다시 생성해서는 안된다는 것을 알릴 수 있습니다 (예 : 백 스택에있는 경우).

Intent h = NavUtils.getParentActivityIntent(this); 
h.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); 
NavUtils.navigateUpTo(this, h);

이 코드는 나를 위해 일했습니다.

Intent upIntent = NavUtils.getParentActivityIntent(this);
if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
    // This activity is NOT part of this app's task, so create a new task
    // when navigating up, with a synthesized back stack.
    TaskStackBuilder.create(this)
        // Add all of this activity's parents to the back stack
        .addNextIntentWithParentStack(upIntent)
        // Navigate up to the closest parent
        .startActivities();
} else {
    // This activity is part of this app's task, so simply
    // navigate up to the logical parent activity.
    upIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    NavUtils.navigateUpTo(this, upIntent);
}

return true;

finish () 호출이 필요하지 않습니다.


Android 4.1 (API 레벨 16)부터 요소에 android : parentActivityName 속성을 지정하여 각 활동의 논리적 상위를 선언 할 수 있습니다. 앱이 Android 4.0 이하를 지원하는 경우 앱에 지원 라이브러리를 포함하고. 그런 다음 android : parentActivityName 속성과 일치하는 android.support.PARENT_ACTIVITY의 값으로 상위 활동을 지정하십시오.

<application ... >
...
<!-- The main/home activity (it has no parent activity) -->
<activity
    android:name="com.example.myfirstapp.MainActivity" ...>
    ...
</activity>
<!-- A child of the main activity -->
<activity
    android:name="com.example.myfirstapp.DisplayMessageActivity"
    android:label="@string/title_activity_display_message"
    android:parentActivityName="com.example.myfirstapp.MainActivity" >
    <!-- Parent activity meta-data to support 4.0 and lower -->
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.example.myfirstapp.MainActivity" />
</activity>

상위 활동에 시작 모드가 있거나 업 인 텐트에 FLAG_ACTIVITY_CLEAR_TOP가 포함 된 경우 상위 활동이 스택의 맨 위로 이동하고 onNewIntent () 메서드를 통해 인 텐트를 수신합니다.

<activity
        android:launchMode="singleTop"
        android:name="com.example.myfirstapp.MainActivity">

    </activity>

In Above Code "SingleTop" ,a new instance of a "singleTop" activity may also be created to handle a new intent. However, if the target task already has an existing instance of the activity at the top of its stack, that instance will receive the new intent (in an onNewIntent() call); a new instance is not created.

For Detail Documentation Click Here

To navigate up when the user presses the app icon, you can use the NavUtils class's static method, navigateUpFromSameTask(). For That Read The Documentaion given in the Link Above.


What works for me (and I also think the cleanest) is to reorder the activity to front. If it doesn't exist on the stack it will be created as you 'nav up'.

Intent upIntent = NavUtils.getParentActivityIntent(this);
upIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(upIntent);
finish();
return true;

you just need to go back , not to create the activity again.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            super.onBackPressed();
            return true;
    }
    return super.onOptionsItemSelected(item);
}

참고URL : https://stackoverflow.com/questions/15559838/actionbar-up-navigation-recreates-parent-activity-instead-of-onresume

반응형