先上一个这个程序的效果图
这个小程序比较简单,结构也比较清晰,但是当时分析的时候还是遇到了一点问题,现在将遇到的问题总结下来
问题一: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);
- }
- }
刚开启这个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>
- <!-- Provides search suggestions for words and their definitions. -->
- <provider android:name="DictionaryProvider"
- android:authorities="dictionary"
- android:syncable="false" />
而对于Intent.ACTION_SEARCH这个Intent是在当我点击系统的搜索框右面的按钮时触发的,触发完之后ListView里面也有了相应的数据。
分析二:Dictionary单例模式的分析
- public class Dictionary {
- private static final Dictionary sInstance = new Dictionary();
- public static Dictionary getInstance() {
- return sInstance;
- }
- private Dictionary() {
- }
- Dictionary.getInstance().ensureLoaded(getResources());
- Dictionary.Word theWord = Dictionary.getInstance().getMatches(word).get(0);