我在通过 Android 片段中的 ArrayAdapter 更新 ListView 时遇到问题。
我有一个处理从服务器检索到的 .csv 的方法。它解析 .csv 并执行以下操作:
for(int i =0; i< lines.length; i++){
String[] words = lines[i].split(",");
for(int j = 0;j<words.length; j++)
if ( j%6 == 1 || j%6 == 2)
getArrayAdapter().add(words[j]);
使用断点,我可以看到“words[j]”是一个有效的字符串。getArrayAdapter 方法如下:
private ArrayAdapter<String> getArrayAdapter(){
if (aa == null){
ListView lv = (ListView) getCurrentActivity().findViewById(R.id.list);
aa = new ArrayAdapter<String>(
getCurrentActivity(),
android.R.layout.simple_list_item_1);
aa.setNotifyOnChange(true);
lv.setAdapter(aa);
}
return aa;
}
如果“getArrayAdapter().add(words[j]);” 被调用时,ArrayAdapter 中的方法“notifyDataSetChanged()”被调用,因为它应该:
@Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
mNotifyOnChange = true;
}
通过其父级,它到达执行此操作的 DataBaseObservable:
public void notifyChanged() {
synchronized(mObservers) {
// since onChanged() is implemented by the app, it could do anything, including
// removing itself from {@link mObservers} - and that could cause problems if
// an iterator is used on the ArrayList {@link mObservers}.
// to avoid such problems, just march thru the list in the reverse order.
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onChanged();
}
}
}
观察者数组有一个“AdapterDataSetObserver”,其中包含对我的适配器和 ListView 的所有类型的引用。我查看了 AdapterDataSetObserver 的 onChanged() 中发生了什么,但我真的不知道该看什么。
我的 table_fragment.xml 看起来像:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/top">
<ListView android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="2"
android:numColumns="2"
android:columnWidth="30dp"
android:id="@+id/list">
</ListView>
</LinearLayout>
包含 Fragment 的活动的 xml 如下所示:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity" >
<fragment android:name="com.example.TableFragment"
android:id="@+id/table_fragment"
android:layout_weight="0"
android:layout_width="match_parent"
android:layout_height="0dip" />
</LinearLayout>
在查看日志时,没有什么奇怪的。一切似乎都很好,但屏幕没有显示任何字符串。
我在这里想念什么?可能缺少一些微不足道的东西,因为我是 Android 的新手。