API Demo SearchableDictionary代码分析一

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


这个小程序比较简单,结构也比较清晰,但是当时分析的时候还是遇到了一点问题,现在将遇到的问题总结下来

问题一: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);程序中用到的时候其实用到的都是一个实例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值