是將查詢結果顯示在 SearchResultActivity,如果我想將查詢結果顯示在 MainActivity 呢?
可以的,只要稍加修改,將部份程式碼從 SearchResultActivity 搬到 MainActivity 就行了
AndroidManifest.xml 內容:
... ... <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <!-- Points to searchable activity so the whole app can invoke search. --> <meta-data android:name="android.app.default_searchable" android:value=".MainActivity" /> <activity android:name=".MainActivity" android:launchMode="singleTop"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <action android:name="android.intent.action.SEARCH" /> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> <meta-data android:name="android.app.searchable" android:resource="@xml/searchable"/> </activity> </application>
activity_main.xml 內容:
<RelativeLayout ... ...> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="search result" android:id="@+id/txt1"/> </RelativeLayout>
MainActivity 內容:
... ... import android.app.SearchManager; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuInflater; import android.support.v7.widget.SearchView; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView txt1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txt1 = (TextView) findViewById(R.id.txt1); // 注意這一行指令 handleIntent(getIntent()); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.options_menu, menu); // Associate searchable configuration with the SearchView SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView(); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); // 顯示完成鈕 searchView.setSubmitButtonEnabled(true); return true; } @Override protected void onNewIntent(Intent intent) { handleIntent(intent); } private void handleIntent(Intent intent) { if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY); txt1.setText("傳遞的查詢字串為 "+query.toString()); } } }