【问题标题】:Can't update a ListView adapter in ListFragment无法更新 ListFragment 中的 ListView 适配器
【发布时间】:2015-12-20 00:29:14
【问题描述】:

我有一个 ListFragment,其中创建了一个 ArrayAdapter 并将其附加到 ListView。我可以在 lv.setAdapter(adapter) 之前设置第一个列表项并且它可以工作,但此后我无法使用 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>

【问题讨论】:

    标签: android android-arrayadapter android-listfragment


    【解决方案1】:

    在视图寻呼机中你可以试试这个

    updateFragment = (UpdateFragment) adapter.instantiateItem(
                                pager, possition);
                        if (updateFragment != null)
                            updateFragment.Update();
    

    或者片段交易你可以通过findview by tag找到一个片段 并调用片段方法

    public interface UpdateFragment {
    
        void Update();
    
    } 
    

    在你的片段中实现这个监听。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-09
      • 2020-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多