Android:Spinner显示来自Web服务的内容

时间:2012-06-13 17:27:12

标签: android user-interface android-asynctask spinner

我想做这样的事情:

主要目标是显示从某些Web服务加载的微调器内容。

用户点击微调器 - 适配器应显示一些文本,例如“loading ...”。当它最终被加载时 - 它应该用加载的内容替换微调器中的现有适配器。

我做了什么:我为它做了一个微调器 onTouchListener 。在Listener中,我正在启动 asyncTask ,它从Web服务下载数据。在 asyncTask onPostExecute 中,我正在尝试替换spinners adapter并执行 spinner.performClick()。但事实上,用户同时看到2个适配器 - 初始一个(“正在加载......”)和新的适配器,由 spinner.performClick()显示。

有没有更好的想法如何完成初始任务或如何只显示一个适配器?

以下是我使用的一些代码:

private class CountryRegionCity extends AsyncTask<String, Void, JSONArray> {
    protected JSONArray doInBackground(String... params) {
        // Getting contents from web service            
        {...}
        return someJSONArray;
    }

        protected void onPostExecute (JSONArray jsonArray) {

        ArrayList<String> countryNames = new ArrayList<String>();
        //Filling here countryNames based on jsonArray
        {...}

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, countryNames);

        mCountrySpinner.setAdapter(adapter);
        mCountrySpinner.performClick();
    }
}

public View onCreateDialogView() {

    ArrayAdapter<String> countryArrayAdapter=new ArrayAdapter<String> (context(), android.R.layout.simple_spinner_item, new String[] {"Loading..."});
    mCountrySpinner.setAdapter(countryArrayAdapter);

    mCountrySpinner.setOnTouchListener(new OnTouchListener() {      
            public boolean onTouch(View v, MotionEvent event) {
                CountryRegionCity getCountries = new CountryRegionCity();
                getCountries.execute("countries");
                return false;
            }
        });
}

1 个答案:

答案 0 :(得分:1)

我猜你可以使用Spinner控件的notifyDataSetChanged()方法来显示适配器数据的变化。