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

时间:2017-02-16 16:32:06

标签: android adapter android-arrayadapter auto-update

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

    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”选项。

任何人都知道如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

请注意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) {

    }
});