And*_*rew 59 android android-intent
我有一个搜索屏幕,可以通过点击另一个屏幕的"名称"字段启动.
如果用户遵循此工作流程,我会在Intent的Extras中添加一个名为"search"的额外内容.此额外使用填充"name"字段的文本作为其值.创建搜索屏幕时,该额外用作搜索参数,并为用户自动启动搜索.
但是,由于Android会在屏幕旋转时销毁并重新创建活动,因此旋转手机会再次导致自动搜索.因此,我想在执行初始搜索时从Activity的Intent中删除"搜索"额外内容.
我试过这样做:
Bundle extras = getIntent().getExtras();
if (extras != null) {
if (extras.containsKey("search")) {
mFilter.setText(extras.getString("search"));
launchSearchThread(true);
extras.remove("search");
}
}
Run Code Online (Sandbox Code Playgroud)
但是,这不起作用.如果我再次旋转屏幕,活动的意图的额外内容中仍然存在额外的"搜索".
有任何想法吗?
And*_*rew 134
我有它的工作.
似乎getExtras()创建了 Intent的附加组件的副本.
如果我使用以下行,这可以正常工作:
getIntent().removeExtra("search");
Run Code Online (Sandbox Code Playgroud)
源代码 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;
}
Run Code Online (Sandbox Code Playgroud)
虽然@Andrew 的回答可能提供了一种删除特定 Intent extra 的方法,但有时需要清除所有 Intent Extras,在这种情况下,您将需要使用
Intent.replaceExtras(new Bundle())
Run Code Online (Sandbox Code Playgroud)
的源代码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;
}
Run Code Online (Sandbox Code Playgroud)
可以使用在破坏和重新创建期间持久的额外标志来解决该问题.这是缩小的代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29254 次 |
| 最近记录: |