我有一个“类别”列表,它们作为字符串存储在我的应用程序的 ArrayAdapter 中。这很简单。适配器是活动的一个字段,可以在任何地方访问。它是在 onCreate() 期间填充值的。
我有一个“条目”对话框,其中包含一个 AutoCompleteTextView,它使用此适配器并且工作得很好。这基本上是一个将新项目添加到列表的对话框。
我还有第二个对话框,它充当列表的过滤器,并且有一个 Spinner,当创建对话框时,它使用相同的 ArrayAdapter。问题就在这里。
如果我在条目对话框之前使用过滤器对话框,则微调器将填充适配器中的所有项目。效果很好。
每次我使用输入对话框时,AutoCompleteTextView 都会正常工作。
如果我使用条目对话框并在 AutoCompleteTextView 出现建议时选择一个项目,就会出现问题。在弹出窗口中选择建议的项目后,即使我取消输入对话框,下次打开过滤器对话框时,微调器最初会显示上次从 AutoCompleteTextView 中选择的项目(而不是适配器中的第一个项目) ,并且仅在单击/触摸时才显示微调器列表中的单个项目。解决此问题的唯一方法是结束应用程序并重新打开它。我在 logcat 中没有收到任何错误或任何有用的信息。
编辑-好的,我已经删除了以前的代码,用我生成的一个简单的测试用例替换它。最重要的是,我想知道这是否是一个错误,或者是否是预期的结果。当在 AutoCompleteTextView 中选择建议时,我可以确认链接到它的 ArrayAdapter 已应用过滤,因此它的计数会受到影响,并且如果在 Spinner 中访问适配器,则显示的唯一项目将是那些被过滤到的项目。我还添加了按钮来显示 toast 以表明计数受到影响。在自动完成中输入“te”,选择任一测试条目。他们尝试旋转器或单击按钮,发现适配器的数量仅为 2。
所以现在最后一个问题是......适配器的过滤器是否可以重置(除了通过输入并清除 AutoCompleteTextView 之外)?我找不到任何方法来做到这一点。我通过设置临时适配器、复制主适配器项目并将视图设置为使用临时适配器来解决实际应用程序中的问题。我的手机运行的是 2.2,我在模拟器中测试了高达 2.3.3 API 级别 10。
main.xml 的 xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<AutoCompleteTextView android:id="@+id/actv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<Spinner android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<Button android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Check It"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true" />
</RelativeLayout>
MainActivity.java 的代码
public class MainActivity extends Activity {
/** Called when the activity is first created. */
AutoCompleteTextView actv;
Spinner spinner;
Button button;
String [] adapterList = {"Test1", "Test2", "Garbage1", "Garbage2"};
ArrayAdapter<String> adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, adapterList);
actv = (AutoCompleteTextView) findViewById(R.id.actv);
spinner = (Spinner) findViewById(R.id.spinner);
button = (Button) findViewById(R.id.button);
actv.setAdapter(adapter);
spinner.setAdapter(adapter);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "" + adapter.getCount() + " Items in Adapter", Toast.LENGTH_SHORT).show();
}
});
}
}