有人知道如何实现标准的教程或示例Android search interface使用 Fragment
吗?换句话说,是否可以在 Fragment 中使用 SearchManager
进行标准搜索?
最佳答案
简而言之,你不能。无法在 Fragment
中创建搜索界面的原因有很多。
创建可搜索界面时,您必须在 Android list 中指定默认的“可搜索 Activity ”。我相信你知道,没有父
Activity
就不能存在Fragment
,因此这种分离是不可能的。如果你已经想出了#1,我假设你问这个问题是希望有一些神奇的“黑客”可以完成工作。但是,文档指出,
When the user executes a search in the search dialog or widget, the system starts your searchable activity and delivers it the search query in an Intent with the ACTION_SEARCH action. Your searchable activity retrieves the query from the intent's QUERY extra, then searches your data and presents the results.
负责提供搜索结果的底层内部系统需要一个
Activity
,而不是Fragment
;因此,实现完全独立于Activity
的搜索界面是不可能的,因为它需要更改底层系统本身。查看SearchableInfo
的源代码如果您不相信我,请上课:)。
话虽如此,实现与您所描述的类似的东西似乎并不难。例如,您可能会考虑实现您的可搜索 Activity ,以便它接受 android.intent.action.SEARCH
Intent 并且(而不是立即在 ListView
中显示结果,例如)会将搜索查询传递给您的 Fragment
s。例如,考虑以下可搜索的 Activity:
public class SearchableActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Intent.ACTION_SEARCH.equals(getIntent().getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
doMySearch(query);
}
}
/**
* Performs a search and passes the results to the container
* Activity that holds your Fragments.
*/
public void doMySearch(String query) {
// TODO: implement this
}
}
当发出搜索请求时,系统将启动您的可搜索 Activity ,执行查询,并将结果传递给某个容器 Activity (基于您的 doMySearch
实现)。然后,容器 Activity 会将这些结果传递给包含的可搜索 Fragment
,结果将在其中显示。该实现需要比您可能希望的更多的工作,但我确信您可以通过一些方法使其更加模块化,而且这似乎是您能做的最好的。
附言如果您使用这种方法,您可能需要特别注意哪些 Activity 被添加/删除到 backstack。看到这个post有关如何完成此操作的更多信息。
p.p.s.您也可能完全忘记了标准搜索界面,而只在 Fragment
中实现一个简单的搜索,如 Raghav's post below 中所述。 .
关于java - 使用 Fragments 进行 Android 搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7230893/