可以通过编程在 Android 应用程序中打开 Spinner 吗?

如果你在 Android 活动中有一个 旋转对象的句柄,你可以通过编程打开 spinner 选项——从而迫使用户选择一个选项,即使他们自己没有点击 Spinner

48637 次浏览

To open the Spinner you just need to call it's performClick() method.

Keep in mind that you may only call this method from the UI thread. If you need to open the Spinner from a separate thread you should create a Handler in the UI thread and then, from your second thread, send a runnable object that calls performClick() to the Handler.

package com.example.SpinnerDemo;


import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.os.Handler;


public class SpinnerDemo extends Activity {


private Handler h;
private Spinner s;


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);


h = new Handler();


s = (Spinner) findViewById(R.id.spinner);
ArrayAdapter adapter = ArrayAdapter.createFromResource(this,
R.array.planets, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);


// Open the Spinner...
s.performClick();


// Spawn a thread that triggers the Spinner to open after 5 seconds...
new Thread(new Runnable() {
public void run() {
// DO NOT ATTEMPT TO DIRECTLY UPDATE THE UI HERE, IT WON'T WORK!
// YOU MUST POST THE WORK TO THE UI THREAD'S HANDLER
h.postDelayed(new Runnable() {
public void run() {
// Open the Spinner...
s.performClick();
}
}, 5000);
}
}).start();
}
}

The resources used by this example can be found here.

You don't need to use 2 runnables as shown in the previous example.

This will be enough :

h.postDelayed(new Runnable() {
public void run() {
s.performClick();
}
}, 5000);

To show the Spinner items you just need to call it's performClick() method.

Spinner spDeviceType = (Spinner) findViewById(R.id.spDeviceType);
spDeviceType.performClick();

Simply use this

yourspinner.performClick();
@Override
protected void onResume() {
super.onResume();
_spinner_operations.performClick();
}

you need the call in onResume, in onCreate this not work.

You can call performClick() after the UI thread is done with its current operation(s). If you don't use post {}, you may not see the Spinner open.

findViewById<Spinner>(R.id.spinner).post {
performClick()
}