在Android中异步调用spinner视图时出现缩小的原因

时间:2017-10-08 16:45:33

标签: java android drop-down-menu android-spinner

背景

当我使用资源数组填充微调器时,一切正常:

Spinner countryCodeSpinner = (Spinner) findViewById(R.id.country_code_spinner);
countryCodeSpinner.setOnItemSelectedListener(this);

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.country_codes_array, android.R.layout.simple_spinner_item);

从资源中读取国家/地区代码:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array
        name="country_codes_array">
        <item>971</item>
        <item>961</item>
        <item>628</item>
        <item>193</item>
        <item>477</item>
    </string-array>
</resources>

输出: enter image description here

问题

但是当我从这样的api调用中填充微调器内容时:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ..
    Spinner currencySpinner = (Spinner) findViewById(R.id.currency_spinner);
    populateCurrency(currencySpinner);

private void populateCurrency(final Spinner spinner) {
    _currencies = new HashMap<String, String>();
    final Context context = this;
    // getting the contents of spinner from api call
    new SyncHelper().get(CreateOrderActivity.this,
            Connections.CURRENCIES(CreateOrderActivity.this),
            null, null, new SyncListener() {
                @Override
                public void onSuccess(String data, int requestCode) {
                    try {

                        JSONObject object = new JSONObject(data);
                        if (object.getString("errors") == "false") {
                            JSONArray currenciesArray = object.getJSONObject("data")
                                    .getJSONArray("currencies");
                            for (int i=0; i< currenciesArray.length(); i++) {
                                String currencyRef = currenciesArray.getJSONObject(i).getString("ref");
                                String currencyId = currenciesArray.getJSONObject(i).getString("id");
                                _currencies.put(currencyRef, currencyId);
                            }

                            String[] currencyrefs = Arrays.copyOf(_currencies.keySet().toArray(),
                                    _currencies.keySet().toArray().length, String[].class);
                            ArrayAdapter<String> adapter =
                            new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item,currencyrefs);
                            spinner.setAdapter(adapter);

然后微调器渲染的视图像这样缩小:

enter image description here

即使在这两种情况下,我们都在使用android.R.layout.simple_spinner_item ..任何想法如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我无法重现这个问题,对我来说,第一个示例给出了类似于第二个示例的输出,第二个示例给出了相同的输出(没有边距,高度设置为wrap_content,也适用于第二个示例,我只使用相同的适配器构造函数来模拟)。行为的差异可能是因为不同的API(我使用了带有API 26的模拟器)。

但是,对我来说,您的第一个和所需的输出看起来像simple_spinner_dropdown_item而不是simple_spinner_item,我能够生成一个带有simple_spinner_dropdown_item的类似微调器,所以您可能想要查看它。