我们假设以下内容:
Activity A calls Search Manager
User searches, and search results are displayed in Activity B
User clicks on a list item in Activity B
App switches back to Activity A
我无法处理从活动B到活动A的回调,因为我没有搜索管理器意图(我认为?)。
呼叫搜索管理器(在活动A中)
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.add_symbol:
onSearchRequested(); //result of search will show Activity B
return true;
default:
return super.onOptionsItemSelected(item);
}
}
用户选择列表项后返回活动A
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Quote myQuote = new Quote();
myQuote.name = (companies.get(position).name);
myQuote.symbol = (companies.get(position).symbol);
//TODO: add new quote to master quote list in Main
//TODO: serialize in Main
//TODO: go back to last activity
Intent myIntent = new Intent(getApplicationContext(), Main.class);
startActivityForResult(myIntent, PICK_COMPANY_REQUEST);
}
});
在活动A中处理回调:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_COMPANY_REQUEST) {
if (resultCode == RESULT_OK) {
Toast toast = Toast.makeText(getApplicationContext(), "Stock added", Toast.LENGTH_SHORT);
toast.show();
}
}
}
PICK_COMPANY_REQUEST
永远不会被发送回去。为什么是这样?我假设因为搜索管理器具有意图,而不是活动B.我如何确保调用它?
onActivityResult()。为什么?
答案 0 :(得分:5)
我在Android onSearchRequested() callback to the calling activity
发布了我认为同样问题的答案 Skythe是正确的,onActivityResult
未被调用,因为活动A没有开始搜索活动的结果。
为了解决这个问题,我将Activity A定义为可搜索的actvity(在清单中),以便它接收搜索意图,然后用startActivityForResult
手动启动Activity B,传入查询并让它们通过活动B正常处理搜索。
您可以在上面的链接中看到我的回复,或者我有more detailed write-up in this blog post。
答案 1 :(得分:1)
未调用onActivityResult,因为startActivityForResult未用于启动搜索活动。我也遇到了这个问题,还没有找到解决方案!
答案 2 :(得分:0)
我真的怀疑你是否需要在onclickListener上调用Main活动的新意图。 由于活动已经在堆栈中,您可以完成它
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Quote myQuote = new Quote();
myQuote.name = (companies.get(position).name);
myQuote.symbol = (companies.get(position).symbol);
//TODO: add new quote to master quote list in Main
//TODO: serialize in Main
//TODO: go back to last activity
//You need to use setresult here and pass the intent
setResult(RESULT_OK, myIntent );
finish();
}
});