我在 AsyncTask 中使用 jsoup 来获取选项的值和文本,并将它们放入文本/值 TreeMap(排序的 HashMap)中,如下所示:
class TheaterGetter extends AsyncTask<Context, Void, Document> {
private Context context;
@Override
protected Document doInBackground(Context... contexts) {
context = contexts[0];
Document doc = null;
try {
doc = Jsoup.connect("http://landmarkcinemas.com").timeout(10000).get();
} catch (IOException e) {
Log.e("website connection error", e.getMessage());
}
return doc;
}
protected void onPostExecute(Document doc) {
Element allOptions = doc.select("select[id=campaign").first();
Elements options = allOptions.getElementsByTag("option");
options.remove(0);
TreeMap<String, String> theaters = new TreeMap<String, String>();
for (Element option:options) {
theaters.put(option.html(), option.attr("value"));
}
然后我为微调器制作了这个适配器:
public class TreeMapSpinAdapter extends ArrayAdapter{
private Context context;
private TreeMap<String, String> treeMap;
public TreeMapSpinAdapter(Context context, int textViewResourceId, TreeMap<String, String> treeMap){
super(context, textViewResourceId, treeMap.values().toArray());
this.context = context;
this.treeMap = treeMap;
}
@Override
public int getCount() {
return this.treeMap.values().size();
}
@Override
public Object getItem(int arg0) {
return this.treeMap.values().toArray()[arg0];
}
public Object getItem(String key) {
return treeMap.get(key);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView label = new TextView(context);
label.setTextColor(Color.BLACK);
label.setText(treeMap.keySet().toArray()[position].toString());
return label;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
TextView label = new TextView(context);
label.setTextColor(Color.BLACK);
label.setText(treeMap.keySet().toArray()[position].toString());
return label;
}
}
然后,回到我们的 AsyncTask 中,我们像这样设置微调器:
TreeMapSpinAdapter adapter = new TreeMapSpinAdapter(context, android.R.layout.simple_spinner_item, theaters);
final Spinner spinner = (Spinner) ((Activity) context).findViewById(R.id.spinner1);
spinner.setAdapter(adapter);
最后我们像这样调用我们的 AsyncTask:
new TheaterGetter().execute(this);
事物被称为剧院这个和那个,因为在我的例子中,我得到了一个剧院位置列表。