Nice programing

전달 된 의도에서 추가 항목 제거

nicepro 2020. 12. 10. 21:06
반응형

전달 된 의도에서 추가 항목 제거


다른 화면의 "이름"필드를 클릭하여 시작할 수있는 검색 화면이 있습니다.

사용자가이 워크 플로를 따르는 경우 "검색"이라는 Intent의 Extras에 추가 항목을 추가합니다. 이 추가 항목은 "이름"필드를 채우는 텍스트를 값으로 사용합니다. 검색 화면이 생성되면 해당 추가 정보가 검색 매개 변수로 사용되며 사용자에 대한 검색이 자동으로 시작됩니다.

그러나 Android는 화면이 회전 할 때 활동을 파괴하고 다시 생성하기 때문에 휴대 전화를 회전하면 자동 검색이 다시 발생합니다. 이 때문에 초기 검색이 실행될 때 Activity의 Intent에서 "검색"추가를 제거하고 싶습니다.

나는 이렇게 시도했다.

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        if (extras.containsKey("search")) {
            mFilter.setText(extras.getString("search"));
            launchSearchThread(true);
            extras.remove("search");
        }
    }

그러나 이것은 작동하지 않습니다. 화면을 다시 회전하면 "검색"추가 항목이 활동의 ​​의도 추가 항목에 여전히 존재합니다.

어떤 아이디어?


작동하고 있습니다.

getExtras () Intent의 추가 사본생성하는 것으로 보입니다 .

다음 줄을 사용하면 정상적으로 작동합니다.

getIntent().removeExtra("search");

소스 코드 getExtras()

/**
 * Retrieves a map of extended data from the intent.
 *
 * @return the map of all extras previously added with putExtra(),
 * or null if none have been added.
 */
public Bundle getExtras() {
    return (mExtras != null)
            ? new Bundle(mExtras)
            : null;
}

이 문제는 파괴 및 재창조 중에 지속되는 추가 플래그를 사용하여 해결할 수 있습니다. 다음은 좁혀진 코드입니다.

boolean mProcessed;

@Override
protected void onCreate(Bundle state) {
    super.onCreate(state);
    mProcessed = (null != state) && state.getBoolean("state-processed");
    processIntent(getIntent());
}

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    mProcessed = false;
    processIntent(intent);
}

@Override
protected void onSaveInstanceState(Bundle state) {
    super.onSaveInstanceState(state);
    state.putBoolean("state-processed", mProcessed);
}

protected void processIntent(Intent intent) {
    // do your processing
    mProcessed = true;
}

@Andrew의 답변은 특정 인 텐트 추가를 제거하는 수단을 제공 할 수 있지만 때로는 모든 인 텐트 추가를 지워야하며이 경우에는 사용하고 싶을 것입니다.

Intent.replaceExtras(new Bundle())

소스 코드 replaceExtras:

/**
 * Completely replace the extras in the Intent with the given Bundle of
 * extras.
 *
 * @param extras The new set of extras in the Intent, or null to erase
 * all extras.
 */
public @NonNull Intent replaceExtras(@NonNull Bundle extras) {
    mExtras = extras != null ? new Bundle(extras) : null;
    return this;
}

참고 URL : https://stackoverflow.com/questions/4520961/removing-extras-from-passed-in-intent

반응형