如何将用户输入的值添加到 android 中的微调器?

How do I add a user inputted value to a spinner in android?

我创建了一个微调器,其中一个选项是 "Add url"。选择 "add url" 时,它会弹出一个警告,允许用户输入新的 url。所有这些都有效。问题是它不会将新的 url 添加到微调器。我在用户添加新的 url 后通知数组适配器。我该如何解决这个问题,以便将新的 url 值放入微调器中。

这是我的微调器代码:

Spinner spinner = (Spinner) findViewById(R.id.spinner);

// Create an ArrayAdapter using the string array and a default spinner layout
ArrayList<String>urls = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.url_array)));
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, urls);

// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);

spinner.setOnItemSelectedListener(this);

这是我的 onItemSelected() 代码:

public void onItemSelected(AdapterView<?> parent, View view, int pos, long l) {
    if (pos==3) {
        // Set an EditText view to get user input
        final EditText input = new EditText(DeviceServicesActivity.this);

        new AlertDialog.Builder(DeviceServicesActivity.this)
                .setMessage("Enter your Point here")
                .setView(input)
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        Editable editable = input.getText();
                        String newString = editable.toString();

                        urls.add(newString);
                        adapter.notifyDataSetChanged();



                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // Do nothing.
                    }
                }).show();
    }
}

@Override
public void onNothingSelected(AdapterView<?> adapterView) {

}

每当我尝试添加 url 时,我都会在 logcat 中发现此消息: W/InputEventReceiver:已尝试完成输入事件,但输入事件接收器已被释放。

而不是使用

  urls.add(newString);

使用

  adaptor.setNotifyOnChange(true);
  adapter.add(newString);

这可能对您有所帮助