先上一个这个程序的效果图

这个小程序比较简单,结构也比较清晰,但是当时分析的时候还是遇到了一点问题,现在将遇到的问题总结下来
问题一:SearchableDictionary的onCreate()函数中Intent分析
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.main);
mTextView = (TextView) findViewById(R.id.textField);
mList = (ListView) findViewById(R.id.list);
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
// from click on search suggestion results
Dictionary.getInstance().ensureLoaded(getResources());
String word = intent.getDataString();
Dictionary.Word theWord = Dictionary.getInstance().getMatches(word).get(0);
launchWord(theWord);
finish();
} else if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
mTextView.setText(getString(R.string.search_results, query));
WordAdapter wordAdapter = new WordAdapter(Dictionary.getInstance().getMatches(query));
mList.setAdapter(wordAdapter);
mList.setOnItemClickListener(wordAdapter);
}
}刚开始对与Intent.ACTION_VIEW和Intent.ACTION_SEARCH的处理不是很清楚,之前做的项目一般都是设置Activity不能从onCreate()重新启动,而这里是从onCreate重新启动的。
刚开启这个Activity的时候这个ListView里面是没有值的,所以只显示了TextView的信息,所以看到下面都是黑色的。当点击搜索按钮的时候,调用系统的搜索框,当我输入要查询的单词时,例如像上面的效果图我输入了“g”,然后下面就会列出词库中所有以g开头的单词,当时对这一点不知道为什么,后来发现是因为搜索的那个xml里面的有相关的配置信息。
searchable.xml
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="@string/search_label"
android:searchSettingsDescription="@string/settings_description"
android:includeInGlobalSearch="true"
android:searchSuggestAuthority="dictionary"
android:searchSuggestIntentAction="android.intent.action.VIEW">
</searchable>android:searchSuggestAuthority="dictionary"这个表示的是当搜索的时候下面提示的数据的来源从ContentProvider里面获取这个早Manifest里面有相应的配置:
<!-- Provides search suggestions for words and their definitions. -->
<provider android:name="DictionaryProvider"
android:authorities="dictionary"
android:syncable="false" />这只是说明了自动提示的功能,还没有说明上面在onCreate里面的两个Intent的作用,对于Intent.ACTION_VIEW这个是在当我点击提示的列表项时触发的,android:searchSuggestIntentAction="android.intent.action.VIEW",这个就说明了,当我出发这些提示信息时这个Intent是什么类型的。这里没有跳转到其他的Activity还是在这个Activity里面所以在onCreate里面处理。
而对于Intent.ACTION_SEARCH这个Intent是在当我点击系统的搜索框右面的按钮时触发的,触发完之后ListView里面也有了相应的数据。
分析二:Dictionary单例模式的分析
public class Dictionary {
private static final Dictionary sInstance = new Dictionary();
public static Dictionary getInstance() {
return sInstance;
}
private Dictionary() { }
}这里的Directory采用了懒汉式的单例模式,因为在整个程序中这个Directory只需要初始化一次。
Dictionary.getInstance().ensureLoaded(getResources());
Dictionary.Word theWord = Dictionary.getInstance().getMatches(word).get(0);程序中用到的时候其实用到的都是一个实例
本文详细解读了一个Android应用中如何利用Intent处理用户搜索行为,并结合Dictionary单例模式进行词库加载与匹配的过程。通过分析Intent.ACTION_VIEW和Intent.ACTION_SEARCH的用途,解释了自动搜索提示和搜索结果呈现的实现原理。同时深入探讨了Dictionary单例模式的使用,阐述了其在简化应用逻辑、提高效率方面的作用。

被折叠的 条评论
为什么被折叠?



