为什么Spinner不触发onItemselected?

时间:2019-11-03 17:33:17

标签: java android xml spinner

我使用此Java代码来编码Android RPN计算器。现在,我处于单击微调器的阶段,设置了显示的小数位数。不幸的是,名为onItemselected的Toast函数不起作用,我认为这意味着未调用该函数。有什么想法吗?

谢谢!

public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {

TextView stackedit0;
LinkedList<Double> fifo = new LinkedList<Double>();
int stack = 0;
int initialized = -1;
double m;

private Spinner spinner;
private static final List<String> paths = new ArrayList<String>();

public void create_string() {

    for (int i=0; i<=1047; i++){

        paths.add(String.valueOf(i));

    }
}

public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {

    Toast.makeText(this, parent.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();

}


public void onNothingSelected(AdapterView<?> parent) {
    // TODO Auto-generated method stub
}
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    spinner = (Spinner)findViewById(R.id.spinner);
    ArrayAdapter<String>adapter = new ArrayAdapter<String>(MainActivity.this,
            android.R.layout.simple_spinner_item,paths);

    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(this);

    create_string();
...
}

<Spinner
            android:id="@+id/spinner"
            android:layout_width="52dp"
            android:layout_height="19dp"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="4dp"
            android:layout_marginRight="4dp"
            android:background="#66000000"
            android:text="AC"
            android:textColor="#FFFFFF"
            android:spinnerMode="dropdown"/>

1 个答案:

答案 0 :(得分:0)

在适配器初始化后填充列表时,可以调用

adapter.notifyDataSetChanged();

在填充列表之后,即在create_string()方法之后,或在填充列表之后初始化适配器。