菜單,下拉選擇,自動完成 學習筆記

主文件

package com.tang.menu;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Spinner;
import android.widget.Toast;
import android.os.Build;

public class MainActivity extends Activity {
	private Spinner sp;
	private AutoCompleteTextView av;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		//下拉;
		sp = (Spinner) findViewById(R.id.sp);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
				android.R.layout.simple_spinner_dropdown_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		adapter.add("java");
		adapter.add("php");
		adapter.add("nodejs");
		sp.setAdapter(adapter);
		
		//自動完成
		String[] names = new String[]{"老一","老二","老三","abc","acd","bc"};
		av = (AutoCompleteTextView) findViewById(R.id.av);
		ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, 
				android.R.layout.simple_dropdown_item_1line, names);
		av.setAdapter(adapter1);
	}
	
	/**
	 * 建立菜單
	 */
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	/**
	 * 選擇菜單
	 */
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		switch (id) {
		case R.id.item1:
			Toast.makeText(this, "item1", 0).show();
			break;

		case R.id.item2:
			Toast.makeText(this, "item2", 0).show();
			break;
		}
		return true;
	}
	
}

menu資源文件

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.tang.menu.MainActivity" >

    <item
        android:id="@+id/item1"
        android:title="第一個菜單"/>
    <item
        android:id="@+id/item2"
        android:title="第二個菜單"/>
    <item
        android:id="@+id/item3"
        android:title="第三個菜單"/>    
</menu>

視圖文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

 <Spinner
    android:id="@+id/sp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"   
     />
 
 <AutoCompleteTextView 
    android:id="@+id/av"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"    
     />

</LinearLayout>
相關文章
相關標籤/搜索