我正在尝试在当前的Android应用程序中实现搜索小部件,但就是无法完成它,
我一直未能实现它。以下是我的代码。
主要活动(MainActivity):
![Google I/O app](https://istack.dev59.com/sTgSN.webp)
主要活动(MainActivity):
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.search_bar).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
} else if (id == R.id.search_bar) {
//startActivity(new Intent(this, SearchResultActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
菜单项
<item android:id="@+id/search_bar"
android:title="Search"
android:orderInCategory="100"
android:icon="@android:drawable/ic_menu_search"
app:showAsAction="always|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"/>
SearchActivity
public class SearchResultActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_custom_text);
handleIntent(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
}
}
}
清单文件
<activity android:name=".MainActivity"
android:enabled="true">
<!--<meta-data android:name="android.app.searchable"
android:resource="@xml/searchable"/>-->
<meta-data android:name="android.app.default_searchable"
android:value=".SearchResultActivity"/>
</activity>
<activity android:name=".SearchResultActivity"
android:enabled="true"
android:launchMode="singleTop"
android:parentActivityName=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.SEARCH"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<!--<meta-data android:name="android.app.default_searchable"
android:value=".SearchResultActivity" />-->
<meta-data android:name="android.app.searchable"
android:resource="@xml/searchable"/>
</activity>
这是我正在考虑的,但我还没有尝试过。我在我的项目中实现了一个浮动活动。从下面的外观来看,我认为它是一个浮动活动。
任何帮助都将不胜感激。