目标效果
在页面中包含一个AutoCompleteTextView控件和一个搜索按钮,当用户点击按钮后,以消息提示框的方式显示文本框里的内容。
文件布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:background="@drawable/bg" >
<AutoCompleteTextView
android:id="@+id/auto"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:completionHint="请输入要搜索的内容~"
android:completionThreshold="2"
android:singleLine="true"/>
<Button
android:id="@+id/find"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="搜索"/>
</LinearLayout>
事件响应
package com.example.aotodemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
AutoCompleteTextView auto=null;
Button find=null;
String[] content={"China","Chinese","ChinaHHH","java","javaEE","javascript"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
auto=(AutoCompleteTextView) findViewById(R.id.auto);
find=(Button) findViewById(R.id.find);
//为控件要匹配的数据资源设置适配器及样式
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,content);
auto.setAdapter(adapter);
find.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Toast.makeText(MainActivity.this, auto.getText().toString(), Toast.LENGTH_LONG).show();
}
});
}
@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;
}
}
运行效果