您现在的位置是:首页 > 文章详情

关于 AutoCompleteTextView 不输入文字就显示下拉

日期:2018-05-17点击:443

由于项目要做一个带有下拉提示的输入框,第一时间就想到了AutoCompleteTextView。但是需求和控件还是有一点出入,公司的需求为:点击输入框即可显示提示数据的数据。

我们知道 AutoCompleteTextView 有一个属性是 android:completionThreshold ,在代码中设置为 setThreshold(int)) ,但是默认情况下为输入框输入 2 个字符的时候才会开始提示,最低可以把这两个属性调整为 1,即输入一个字就进行提示。

在查找大量的资料之后我采用了如下的方式进行操作:

public class MainActivity extends AppCompatActivity implements View.OnFocusChangeListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate (savedInstanceState); setContentView (R.layout.activity_main); AutoCompleteTextView tvDemo = findViewById (R.id.tv_demo); //设置弹出列表高度总高度 // tvDemo.setDropDownHeight (100); //设置弹出列表与输入框直接距离 tvDemo.setDropDownVerticalOffset (0); //设置下拉框颜色 tvDemo.setDropDownBackgroundResource (R.color.colorAccent); //设置弹出条目的每个条目高度 // tvDemo.setDropDownHeight (100); List<String> list = new ArrayList<> (); list.add ("aaa"); list.add ("bbb"); list.add ("ccc"); list.add ("ddd"); ArrayAdapter adapter = new ArrayAdapter (this, android.R.layout.simple_expandable_list_item_1, list); tvDemo.setAdapter (adapter); tvDemo.setOnFocusChangeListener (this); } @Override public void onFocusChange(View v, boolean hasFocus) { AutoCompleteTextView view = (AutoCompleteTextView) v; if (hasFocus) { view.showDropDown (); } } } 
操作之后

但是细心的人会发现,进入界面就会弹出软键盘,看上去是不是感觉很不好,解决这个问题仅需要在 AutoCompleteTextView 的父布局内添加两个代码,即可解决问题

android:focusable="true" android:focusableInTouchMode="true" 

完整的xml代码:

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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" android:focusable="true" android:focusableInTouchMode="true" tools:context=".MainActivity"> <AutoCompleteTextView android:id="@+id/tv_demo" android:layout_width="match_parent" android:layout_height="wrap_content" android:completionThreshold="1" android:hint="请输入内容" android:paddingEnd="10dp" android:paddingStart="10dp" /> </RelativeLayout> 
原文链接:https://yq.aliyun.com/articles/632801
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章