1. 程式人生 > >Android開發:Toolbar與SearchView實現搜尋功能

Android開發:Toolbar與SearchView實現搜尋功能

本文內容

本章介紹:用Toolbar和SearchView實現搜尋功能

設定主題
開啟res/values/styles.xml檔案,新增下面程式碼:

    <style name="ThemeNoActionBar" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">#3F51B5</item>
        <item name="colorPrimaryDark">#303F9F</item>
        <item
name="colorAccent">#FF4081</item> <item name="android:textColorPrimary">#00ff00</item> </style>

新增主題
開啟AndroidManifest.xml檔案,配置Activity或Fragment的主題,這裡用的是Activity

 <activity
            android:name=".module.test.TestActivity"
            android:theme="@style/ThemeNoActionBar"
android:label="@string/title_activity_test">
<intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity
>

SearchView的配置檔案
開啟res/menu目錄,建立檔案menu_main.xml檔案

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.bf.offline.MainActivity">
    <!--<item-->
        <!--android:id="@+id/action_settings"-->
        <!--android:orderInCategory="100"-->
        <!--android:title="@string/action_settings"-->
        <!--app:showAsAction="never" />-->

    <item android:id="@+id/search"
        android:title="搜尋"
        app:showAsAction="always"
        app:actionViewClass="android.support.v7.widget.SearchView"
        />
</menu>

app:showAsAction

它有三個可選項

  1. always:總是顯示在介面上
  2. never:不顯示在介面上,只讓出現在右邊的三個點中
  3. ifRoom:如果有位置才顯示,不然就出現在右邊的三個點中

Toolbar的佈局檔案
在res/layout目錄下,建立activity_test.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.happycomehealthy.module.test.TestActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</LinearLayout>

使用Toolbar與SearchView的java檔案

package com.happycomehealthy.module.test;

import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.happycomehealthy.R;
import com.happycomehealthy.module.main.MainActivity;
import com.happycomehealthy.widget.TextItemVew;

//注意這裡不能繼承Activity,而是繼承AppCompatActivity
public class TestActivity extends AppCompatActivity {
    private String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        initToolBar();
    }

    private void initToolBar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);//這句程式碼使啟用Activity回退功能,並顯示Toolbar上的左側回退圖示
    }

    @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);

        // Get the SearchView and set the searchable configuration
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
        // Assumes current activity is the searchable activity
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){
            @Override
            public boolean onQueryTextSubmit(String query) {
                Log.i(TAG,query);
                Toast.makeText(TestActivity.this,query,Toast.LENGTH_SHORT).show();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == android.R.id.home){
            Log.i(TAG,"back");
            Toast.makeText(this,"back",Toast.LENGTH_SHORT).show();
        }
        return true;
    }

}