代码改变世界

AutoCompleteTextView自动完成输入内容

2014-03-21 21:13  kingshow  阅读(261)  评论(0编辑  收藏  举报

 

    有时候,在输入一些内容的,会自动出现相关内容的提示,这在android中有两个控件来完成,下面介绍这两个控件。

AutoCompleteTextView

MultiAutoCompleteTextView

一、建立工程,如图

 

二、activity_main.xml中代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="AutoCompleteTextView" />
    <AutoCompleteTextView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/autotext"
        />
    <TextView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="MultiAutoCompleteTextView"
        />
    <MultiAutoCompleteTextView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/multi"
        />

</LinearLayout>
View Code

三、MainActivity.java中代码

package com.study.autotextview;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.MultiAutoCompleteTextView;

public class MainActivity extends Activity {

    private AutoCompleteTextView auto;
    private MultiAutoCompleteTextView multiAuto;
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        auto = (AutoCompleteTextView)this.findViewById(R.id.autotext);
        String[] autoStrings = new String[]{"联合国","联合国安理会","联合国五个常任理事","Google","google search","百度","百度云"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_dropdown_item_1line,autoStrings);
        auto.setAdapter(adapter);
        
        multiAuto = (MultiAutoCompleteTextView)this.findViewById(R.id.multi);
        multiAuto.setAdapter(adapter);
        multiAuto.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());//完成对选项的拆分的功能,以逗号进行拆分
        
        
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}
View Code

四、效果图