我希望创建一个搜索功能,其中我有一个编辑文本,我在它下面放置了一个微调器。当我在edittext中输入任何内容时,有一个数组,我可以从中比较edittext中输入的字母,过滤数组元素后,我将它们添加到微调器中并打开微调器。
我面临的问题是,当微调器打开时,edittext失去焦点,我需要关闭微调器才能再次开始输入。
我附上代码请任何有任何想法的人请帮助我:
布局:
<?xml version="1.0" encoding="utf-8"?>
<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"
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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<EditText
android:id="@+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusableInTouchMode="true"
/>
<Spinner
android:id="@+id/edit_spinner"
android:layout_width="match_parent"
android:layout_height="0dp"
android:focusableInTouchMode="false"
/>
</LinearLayout>
</RelativeLayout>
活动:
public class MainActivity extends AppCompatActivity {
EditText editText;
Spinner spinner;
ArrayList<String> mylist;
String[] strngarray;
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mylist = new ArrayList<>();
strngarray = getResources().getStringArray(R.array.planets_array);
for(int i=0;i<strngarray.length;i++)
{
mylist.add(strngarray[i]);
}
textView = (TextView) findViewById(R.id.tv);
editText = (EditText) findViewById(R.id.edittext);
spinner = (Spinner) findViewById(R.id.edit_spinner);
adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,(List)mylist);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
Log.d("TextWatcher","before changed Char : "+s);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.d("TextWatcher", "on changed Char : " + s);
if(!s.equals("")) {
mylist.clear();
for (int i = 0; i < strngarray.length; i++) {
String temp = strngarray[i].toLowerCase();
String prefix = s.toString().toLowerCase();
if (temp.startsWith(prefix)) {
mylist.add(strngarray[i]);
}
}
if (mylist.size() != 0) {
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, (List) mylist);
adapter.notifyDataSetChanged();
spinner.performClick();
spinner.clearFocus();
editText.requestFocus();
}
}
}
@Override
public void afterTextChanged(Editable s) {
Log.d("TextWatcher","after changed Char : "+s);
}
});
}
}
答案 0 :(得分:2)