【发布时间】:2013-07-06 14:24:37
【问题描述】:
我在这里要做的是在按下软键上的“Enter/Done”时添加当前在 EditText 中的单词。但是,每次我按软键上的“Enter/Done”时,应用程序都会崩溃。
我尝试进行一些调试,似乎问题出在 adapter.add(v.getText().toString());线。我不知道为什么/如何!!
public boolean onEditorAction(TextView v,int actionId, KeyEvent event) {
Log.d("InThere","in onEditorAction1");
if((event==NULL) || (event.getAction()==KeyEvent.ACTION_UP))
{
if(event==NULL)
Log.d("InThere","inside if+EVENT");
if(event.getAction()==KeyEvent.ACTION_UP)
Log.d("InThere","inside if+ACTION_UP");
Log.d("InThere","before adapter ");
adapter.add(v.getText().toString()); <<<cause of error ?
Log.d("InThere","after adapter ");
v.setText("");
InputMethodManager imm=(InputMethodManager)
getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
Log.d("InThere","in onEditorAction2");
return true;
}
我创建了一个带有“InThere”标签的过滤器,它在 LogCat 中是这样的:
InThere in onEditorAction1
InThere in onEditorAction2
InThere in onEditorAction1
InThere inside if+ACTION_UP
InThere before adapter
另外,你能帮我理解为什么字符串是通过 onEditorAction 函数中的 TextView 实例获取的,而实际上它实际上是从 EditText 获取的?
[更新]
这是代码的声明部分......
private final static String[] items={"this","is","a","really","silly","list"};
private static final KeyEvent NULL = null;
private ArrayList<String> words=null;
private ArrayAdapter<String> adapter;
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
words = new ArrayList<String>();
for(String s: items)
{
words.add(s);
}
adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,items);
setListAdapter(adapter);
}
【问题讨论】:
-
什么是适配器类?
-
是的,什么是适配器类?还要检查您的 LogCat 的堆栈跟踪,即要读取的导入日志!会告诉你确切的错误
-
EditText是TextView的子类developer.android.com/reference/android/widget/EditText.html -
@Blundell 或@Wand Maker:哦!很抱歉。它被声明为
private ArrayAdapter<String> adapter;在同一个类中,即 MainActivity.java -
使用包含 items 值的
ArrayList并将其传递给ArrayAapter。否则,适配器将从您传入的数组中创建一个不可变列表,其中add/remove方法不起作用并抛出您看到的错误。
标签: android runtime-error android-arrayadapter