调用 notifyDataSetChanged() 时 ArrayAdapter 不更新视图

ArrayAdapter does not update view when notifyDataSetChanged() is called

所以我有一段代码看起来像这样

    floorList = new ArrayList<String>();
    arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, floorList);
    arrayAdapter.setNotifyOnChange(true);
    floorSpinner.setAdapter(arrayAdapter);
    floorList.add("a");

    Call<ParkourResponse<ParkingPlaceResponseObject>> getPlaceDetailCall = Helper.getParkourService().getPlaceDetail(placeID);
    getPlaceDetailCall.enqueue(new Callback<ParkourResponse<ParkingPlaceResponseObject>>() {
        @Override
        public void onResponse(Call<ParkourResponse<ParkingPlaceResponseObject>> call, Response<ParkourResponse<ParkingPlaceResponseObject>> response) {
            ParkingPlaceResponseObject placeDetail = response.body().getRespObject();
            Floor[] floorArray = placeDetail.getFloor();
            floorList.clear();
            arrayAdapter.notifyDataSetChanged();
            for(int i = 0; i < floorArray.length; i++){
                floorList.add(Integer.toString(floorArray[i].getNumber()));
            }
        }

        @Override
        public void onFailure(Call<ParkourResponse<ParkingPlaceResponseObject>> call, Throwable t) {

        }
    });

因此,当我尝试添加不属于 Retrofit 服务的 "a" 时,微调器已更新。

但是我在 onResponse() 中对 floorList 所做的一切都不会更新适配器和微调器。 我试图在 onResponse() 上清除它,然后调用 notifyDataSetChanged(),即使这样也不会从微调器中删除 "a" 选项。

有人知道如何解决这个问题吗?

在遵循此答案时请注意 Selvin 和 Gautam 的评论,因为它们是正确的并且将帮助您理解为什么代码应如下所示:

floorList = new ArrayList<String>();
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, floorList);
arrayAdapter.setNotifyOnChange(true);
floorSpinner.setAdapter(arrayAdapter);
arrayAdapter.add("a"); //I would jsut pass this into the adapter's constructor

Call<ParkourResponse<ParkingPlaceResponseObject>> getPlaceDetailCall = Helper.getParkourService().getPlaceDetail(placeID);
getPlaceDetailCall.enqueue(new Callback<ParkourResponse<ParkingPlaceResponseObject>>() {
    @Override
    public void onResponse(Call<ParkourResponse<ParkingPlaceResponseObject>> call, Response<ParkourResponse<ParkingPlaceResponseObject>> response) {
        ParkingPlaceResponseObject placeDetail = response.body().getRespObject();
        Floor[] floorArray = placeDetail.getFloor();
        arrayAdapter.clear(); //update the adapter, not the external list
        arrayAdapter.setNotifyOnChange(false); //we'll only update after list is full, for efficiency
        for(int i = 0; i < floorArray.length; i++){
            arrayAdapter.add(Integer.toString(floorArray[i].getNumber()));
        }
        arrayAdapter.setNotifyOnChange(true);
        arrayAdapter.notifyDataSetChanged();
    }

    @Override
    public void onFailure(Call<ParkourResponse<ParkingPlaceResponseObject>> call, Throwable t) {

    }
});