動做視圖在動做欄中的使用

activity_main.xml 默認不變。html

在res/menu中,修改main.xml,增長4個菜單項,爲第一個設置actionViewClass屬性爲"anroid.widget.SearchView",java

其餘的不設置該屬性:android

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/action_search"
        android:actionViewClass="android.widget.SearchView"
        android:icon="@android:drawable/ic_menu_search"
        android:showAsAction="ifRoom"
        android:title="查詢"/>
    
    <item android:id="@+id/item1"
        android:icon="@drawable/icon1"
        android:showAsAction="always"
        android:title="item1"/>
    
    <item android:id="@+id/item2"
        android:icon="@drawable/icon2"
        android:showAsAction="ifRoom"
        android:title="item2"/>
    
    <item android:id="@+id/item3"
        android:icon="@drawable/icon3"
        android:showAsAction="ifRoom"
        android:title="item3"/>
    

</menu>


ActionViewActivity.java:
app

package com.example.demioactionview;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SearchView;
import android.widget.Toast;

public class ActionViewActivity extends Activity {

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

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		
		SearchView searchView = (SearchView)menu.findItem(R.id.action_search).getActionView();
		searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
			
			@Override
			public boolean onQueryTextSubmit(String query) {
				Toast.makeText(ActionViewActivity.this, "查詢:"+query, Toast.LENGTH_LONG).show();
				return true;
			}
			
			@Override
			public boolean onQueryTextChange(String newText) {
				// TODO Auto-generated method stub
				return true;
			}
		});
		
		
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item){
		Toast.makeText(this, "選擇:"+item.getTitle(), Toast.LENGTH_LONG).show();
		return true;
	}

}
相關文章
相關標籤/搜索