此控件的功能是帮助用户实现自动输入,例如当用户输入一个字符后,能够根据这个字符提示显示出与之相关的数据。里面用到了一个适配器来实现此功能.
源代码如下:
package com.example.autosearch;
import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.TextView;
public class AutoSearch extends Activity {
private String[] normalString = new String[]{
"android","android blog","android market",
"android sdk",
"Java 2SE","java 2me","mobile","IBM","Google"
};
@SuppressWarnings("unused")
private TextView TextView_InputShow;
private AutoCompleteTextView AutoCompleteTextView_Input;
private Button Button_clean;
private ArrayAdapter<String> arrayAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView_InputShow = (TextView)findViewById(R.id.TextView_InputShow);
AutoCompleteTextView_Input = (AutoCompleteTextView)findViewById(R.id.AutoCompleteTextView_Input);
Button_clean = (Button)findViewById(R.id.Button_clean);
//适配器对象的实现,给自动完成输入框添加自动装入的内容
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,normalString);
//给自动输入框添加内容适配器
AutoCompleteTextView_Input.setAdapter(arrayAdapter);
Button_clean.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//清空
AutoCompleteTextView_Input.setText("");
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.auto_search, menu);
return true;
}
}
XML文件如下:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget0"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/TextView_InputShow"
android:layout_width="228px"
android:layout_height="47px"
android:layout_x="42px"
android:layout_y="37px"
android:text="请输入:"
android:textSize="25px" />
<AutoCompleteTextView
android:id="@+id/AutoCompleteTextView_Input"
android:layout_width="275px"
android:layout_height="wrap_content"
android:layout_x="23px"
android:layout_y="98px"
android:text=""
android:textSize="18sp" >
</AutoCompleteTextView>
<Button
android:id="@+id/Button_clean"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="127dip"
android:layout_y="150dip"
android:text="清空" />
</AbsoluteLayout>