安卓控件之Myautocompletetextview(有适配器)

        • 布局文件
        • 主要类文件
          • 有代码注释解析
        • 最后效果:

布局文件

这里布局文件有两个
activity_main.xml:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.bluelesson.myautocompletetextview.MainActivity">

    <AutoCompleteTextView
        android:id="@+id/autocomplete"
        android:completionThreshold="1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

LinearLayout>

item.xml:



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:src="@mipmap/ic_launcher"
        android:layout_width="30dp"
        android:layout_height="30dp" />
    <TextView
        android:id="@+id/text"
        android:textSize="20sp"
        android:text="hah"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
LinearLayout>

主要类文件

有代码注释解析
package com.bluelesson.myautocompletetextview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //1.准备数据源
        final String string[] = {"北京","上海","广州","1235","hello"};
        //2.准备适配器
        ArrayAdapter adapter = new ArrayAdapter(
                MainActivity.this,     //
                R.layout.item,                 //显示的布局
                R.id.text,                     //显示的字符串,下面的适配器就是将布局和字符串两个布局文件关联起来!!!!!!
                string);                       //数据源
        //3.让控件和适配器进行关联
        AutoCompleteTextView autoCompleteTextView = findViewById(R.id.autocomplete);
        autoCompleteTextView.setAdapter(adapter);

        //当点击了某一列响应
        autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView adapterView, View view, int i, long l) {
                Toast.makeText(MainActivity.this,string[i], Toast.LENGTH_LONG).show();
            }
        });
    }
}

最后效果:

安卓控件之Myautocompletetextview(有适配器)_第1张图片

你可能感兴趣的:(安卓开发)