无法更新ListFragment中的ListView适配器

时间:2015-12-20 00:29:14

标签: android android-arrayadapter android-listfragment

我有一个ListFragment,它创建了一个ArrayAdapter并附加到ListView。我可以在lv.setAdapter(适配器)之前设置第一个列表项并且它可以工作,但此后我无法使用addEntry方法从此类外部更新ListView。这可能是什么问题?

public class MyFragment extends ListFragment implements OnItemClickListener {
    public static ArrayAdapter<String> adapter = null;
    public static ListView lv = null;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        adapter = new ArrayAdapter<>(getActivity(), R.layout.listview, R.id.host, new ArrayList<>());
        adapter.setNotifyOnChange(true);
        adapter.add("Entry1");
        lv = getListView();
        lv.setOnItemClickListener(this);
        lv.setAdapter(adapter);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_hostlist, container, false);
        return view;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Toast.makeText(getActivity(), "Item: " + position, Toast.LENGTH_SHORT).show();
    }

    public static void addEntry(String listEntry) {
        Log.d("TAG", "New entry: " + listEntry);
        adapter.add(listEntry);
        adapter.notifyDataSetChanged();
    }
}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/icon"
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:layout_margin="5dp"
        android:src="@drawable/image" />
    <TextView
        android:id="@+id/entry"
        android:layout_margin="5dp"
        android:textSize="20sp"
        android:textColor="#ffffff"
        android:layout_width="match_parent"
        android:layout_height="64dp"
        android:gravity="center_vertical|start"
        android:paddingTop="5dp"/>

</LinearLayout>

0 个答案:

没有答案