Android 自定义AutoCompleteTextView实现显示所有项

本文介绍了如何在Android中自定义AutoCompleteTextView,以达到显示所有数据项的效果,而非传统的自动补全。通过创建custom_auto_complete_view.xml布局文件并提供完整代码下载,作者详细讲解了实现这一特性的过程,并提醒读者在引用时注明出处。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android系统中有AutoCompleteTextView控件可以实现自动补全,其原理实际上就是一个EditText 加一个弹出的列表,通过不断监听EditText中字符的变化来过滤列表中数据,但是这不是我想要的效果,我希望的效果是下面这样的:

废话不多说,直接上代码:

首先是自定义View的布局,custom_auto_complete_view.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:background="@android:color/background_dark"
    >
    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" 
        android:layout_margin="1dp"
    	android:background="@android:color/background_light"
        >
	    <TextView 
	        android:id="@+id/custom_auto_complete_title"
	        android:layout_width="match_parent"
	        android:layout_height="40dp"
	        android:background="@android:color/darker_gray"
	        android:gravity="center_vertical"
	        android:padding="5dp"
	        android:text="标题"
	        android:textSize="18sp"
	        android:textColor="@android:color/black"
	        />
	    <LinearLayout 
	        android:layout_width="match_parent"
	        android:layout_height="wrap_content"
	        android:orientation="horizontal"
	        >
		    <FrameLayout 
		        android:layout_width="0dp"
		        android:layout_height="wrap_content"
		        android:layout_gravity="center_vertical"
		        android:layout_weight="8"
		        >
		            <EditText 
				        android:id="@+id/custom_auto_complete_tv"
				        android:layout_width="match_parent"
				        android:layout_height="wrap_content"
				        android:singleLine="true"
				        android:paddingLeft="40dp"
				        android:background="@drawable/btn_global_search_normal"
			        />
			         <ImageView 
			            android:layout_width="wrap_content"
			            android:layout_height="wrap_content"
			            android:layout_gravity="center_vertical"
			            android:layout_marginLeft="8dp"
			            android:src="@drawable/ic_btn_search"/>
			         <ImageView 
			            android:id="@+id/custom_auto_complete_clear_text"
			            android:layout_width="wrap_content"
			            android:layout_height="wrap_content"
			            android:layout_gravity="center_vertical|right"
			            android:src="@android:drawable/ic_notification_clear_all"/>
		    </FrameLayout>
		    <Button 
		        android:id="@+id/custom_auto_complete_confirm_btn"
		        android:layout_width="0dp"
		        android:layout_height="wrap_content"
		        android:layout_weight="2"
		        android:layout_gravity="center_vertical"
		        android:text="确定"/>
	    </LinearLayout>
		    <ListView 
		        android:id="@+id/custom_auto_complete_listview"
		        android:layout_width="match_parent"
		        android:layout_height="300dp"
		        />
    </LinearLayout>
</LinearLayout>
弹出对话框的布局,dialog_select_autocomplete.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:layout_margin="30dp"
    android:orientation="vertical" 
    android:background="@android:color/background_light">
    
    <com.example.customautocompleteview.CustomAutoCompleteView
        android:id="@+id/CustomAutoCompleteView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
    </com.example.customautocompleteview.CustomAutoCompleteView>
</LinearLayout>
Activity的布局,activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <EditText 
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="20dp"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:onClick="OnViewClick"
        android:text="选择" />

</RelativeLayout>

然后是自定义控件的代码,CustomAutoCompleteView.java:

package com.example.customautocompleteview;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
/**
 * 自定义的可以自动补全数据的选择对话框
 * @author king
 * @creation 2013-8-26
 */
public class CustomAutoCompleteView extends LinearLayout {
	private EditText autoCompleteTextView;
	private ListView listView;
	private ListAdapter mAdapter;
	private Filter mFilter;
	private onValueSelectedListener valueSelectedListener;
	private TextView title;
	public CustomAutoCompleteView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initView(context);
	}

	public CustomAutoCompleteView(Context context) {
		super(context);
		initView(context);
	}

	private void initView(Context context){
		LayoutInflater inflater = LayoutInflater.from(context);
		View view = inflater.inflate(R.layout.custom_auto_complete_view, null);
		autoCompleteTextView = (EditText) view.findViewById(R.id.custom_auto_complete_tv);
		listView = (ListView) view.findViewById(R.id.custom_auto_complete_listview);
		autoCompleteTextView.addTextChangedListener(new MyWatcher());
		Button confirmBtn = (Button) view.findViewById(R.id.custom_auto_complete_confirm_btn);
		ImageView clearText = (ImageView) view.findViewById(R.id.custom_auto_complete_clear_text);
		title = (TextView) view.findViewById(R.id.custom_auto_complete_title);
		listView.setOnItemClickListener(new  AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Object selectedItem = mAdapter.getItem(position);
				CharSequence charSequence = mFilter.convertResultToString(selectedItem);
				autoCompleteTextView.setText(charSequence);
			}
		});
		MyClickListener l = new MyClickListener();
		confirmBtn.setOnClickListener(l);
		clearText.setOnClickListener(l);
		
		addView(view);
	}
	
	public boolean enoughToFilter() {
		return true;
	}

	public <T extends ListAdapter & Filterable> void setAdapter(T adapter) {
		mAdapter = adapter;
		listView.setAdapter(adapter);
		mFilter = adapter.getFilter();
	}

	private class MyWatcher implements TextWatcher{

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			
		}

		@Override
		public void afterTextChanged(Editable s) {
			if(mFilter != null){
				mFilter.filter(autoCompleteTextView.getText());
			}
		}
	}
	
	private class MyClickListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.custom_auto_complete_confirm_btn:
				//确定选择
				if(valueSelectedListener != null){
					valueSelectedListener.onValueSelected(autoCompleteTextView.getText().toString());
				}
				break;
			case R.id.custom_auto_complete_clear_text:
				//清除文本框文字
				autoCompleteTextView.setText("");
				break;
			default:
				break;
			}
			
		}
		
	}
	
	/**
	 * 初始化输入框中的文本
	 * @param initValue
	 */
	public void setInitValue(CharSequence initValue){
		autoCompleteTextView.setText(initValue);
	}
	/**
	 * 设置标题
	 * @param title
	 */
	public void setTitle(String title){
		this.title.setText(title);
	}
	/**
	 * 设置确定选择项的监听器
	 * @param l
	 */
	public void setOnValueSelectedListener(onValueSelectedListener l){
		this.valueSelectedListener = l;
	}
	/**
	 * 当选项被确定选择时触发的监听器
	 * @author king
	 * @creation 2013-8-26
	 */
	public interface onValueSelectedListener{
		public void onValueSelected(String selectedValue);
	}
}

最后,在Activity中调用,MainActivity.java:

package com.example.customautocompleteview;

import android.os.Bundle;
import android.app.Activity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

public class MainActivity extends Activity {

	private EditText edtView;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		edtView = (EditText) findViewById(R.id.text);
	}

	public void OnViewClick(View v){
		showSelectDialog(new String[]{
				"ABCD98S76J","ABCD28S76J","BCD8762","BCESF9765","CDFESAGF","CDFGAWED","ESDFA23","1233ASCA","12ASDF","862ASD"},
				"型号",edtView);
	}

	void showSelectDialog(String[] data, String title, final TextView textView){
		LayoutInflater inflater = LayoutInflater.from(this);
		View view = inflater.inflate(R.layout.dialog_select_autocomplete, null);
		CustomAutoCompleteView autoView =  (CustomAutoCompleteView) view.findViewById(R.id.CustomAutoCompleteView);
		ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
		autoView.setAdapter(arrayAdapter);
		autoView.setTitle(title);
		autoView.setInitValue(textView.getText());
		final PopupWindow popupWindow = new PopupWindow(view, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
		popupWindow.showAtLocation(getCurrentFocus(), Gravity.CENTER, 0, 0);
		autoView.setOnValueSelectedListener(new CustomAutoCompleteView.onValueSelectedListener() {

			@Override
			public void onValueSelected(String selectedValue) {
				textView.setText(selectedValue);
				popupWindow.dismiss();
			}
			
		});
	}
}

完整代码下载:http://download.youkuaiyun.com/detail/kingjxust/6028325

文章出自http://blog.youkuaiyun.com/kingjxust/article/details/10470045,转载请注明出处。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值