本文介绍了我怎样才能改变ArrayAdapter全球,并在另一个类清除它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ArrayAdapter 声明。我想清楚了,并添加一些其他的数据。
所以,我怎样才能将其更改为全球性的?

I have a ArrayAdapter declaration. I want to clear it and add some other data.So how can I change it to global?

public class ForecastFragment extends Fragment {
    private ArrayAdapter<String> mForecastArray;
    // ...
    List<String> weekForecast = new ArrayList<String>(Arrays.asList(forecastArray));
    mForecastArray = new ArrayAdapter<String>(getActivity(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, weekForecast);
    ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
    listView.setAdapter(mForecastArray);
}

另一类

public class FetchWeatherTask extends AsyncTask<String, Void, String[]>{
    protected void onPostExecute(String[] strings) {
        if (strings!=null){
            mForecastArray.clear();
        for (String dayForecast : strings){
            mForecastArray.add(dayForecast);
        }
    }
}

我无法在第二类中使用 mForecastArray

推荐答案

全局变量总是容易出错,并且从长远来看,创造的问题。

Global variables are always error prone and create issues in the long run.

您可以 A 监听器中定义你的的AsyncTask ,将有发言权的方法 updateAdapter ,这会监听你的片段 ForecastFragment 实施。所以一旦你有

You can have a listener defined in your AsyncTask that would have say a method updateAdapter and this listener would be implemented by your Fragment ForecastFragment. So once you you have

public class FetchWeatherTask extends AsyncTask<String, Void, String[]>{

    FetchListener listener;

    public FetchWeatherTask(FetchListener listener) {
        this.listener = listener;
    }

    public interface FetchListener {
        public void updateAdapter(String[] arr);
    }

    protected void onPostExecute(String[] strings) {
        //if (strings!=null){
        //  mForecastArray.clear();
        //for (String dayForecast : strings){               
            //mForecastArray.add(dayForecast);
        //}

        // just call your listener's update method
        listener.updateAdapter(strings);
    }
}

里面ForecastFragment:

public class ForecastFragment extends Fragment implements FetchWeatherTask.FetchListener {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        // say if you are starting your AsyncTask here
        new FetchWeatherTask(this).execute();
    }

    public void updateAdapter(String[] arr) {
        if (arr!=null){
            mForecastArray.clear();

        // use arr to re populate your mForecastArray
    }
}

这篇关于我怎样才能改变ArrayAdapter全球,并在另一个类清除它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 15:50