Android入門教程(十二)之仿百度Google搜尋自動提示框—–AutoCompleteTextView的應用)

來源:互聯網
上載者:User

現在我們上網幾乎都會用百度或者Google搜尋資訊,當我們在輸入框裡輸入一兩個字後,就會自動提示我們想要的資訊,這種效果在Android 裡是如何?的呢? 事實上,AndroidAutoCompleteTextView Widget ,只要搭配ArrayAdapter 就能設計同類似Google 搜尋提示的效果.

 

本例子先在Layout 當中布局一個AutoCompleteTextView Widget ,然後通過預先設定好的字串數組,將此字串數組放入ArrayAdapter ,最後利用AutoCompleteTextView.setAdapter 方法,就可以讓AutoCompleteTextView 具有自動提示的功能.例如,只要輸入ab ,就會自動帶出包含ab 的所有字串列表.

 

讓我們看一下:

 

 

下面是我們程式所涉及變動的代碼(本例子代碼寫的相對較少):

 

首先是main.xml:

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Please input:"
    />
<AutoCompleteTextView
    android:id="@+id/actv"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
/>

</LinearLayout>

其次是主控製程序AutoCompleteTextViewDemo.java:

 

package com.android.test;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

public class AutoCompleteTextViewDemo extends Activity {

    private AutoCompleteTextView actv;
    private static final String[] autoStrs = new String[]{"a","abc","abcd","abcde","ba"};

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        //通過findViewById()方法取到actv
        actv = (AutoCompleteTextView)findViewById(R.id.actv);
        //new ArrayAdapter對象並將autoStr字串數組傳入actv中
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line,autoStrs);  
        actv.setAdapter(adapter);  

    }
}

 

所有程式就這麼一點點哦,大功就這麼告成了,最後執行之,將達到上述效果,今天至此結束,謝謝大家!!!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.