我想从spinner检索值。
这是我的代码

AddCustomerAcitivity.java

public class AddCustomerActivity extends AppCompatActivity{
Spinner spinnerCustomer;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_customer);

    Toolbar toolbar = (Toolbar) findViewById(R.id.add_customer_toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle("Add New Customer");

    fetchId();
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.spinner_category,
            android.R.layout.simple_spinner_item);
  adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerCustomer.setAdapter(adapter);
}

private void fetchId() {
    spinnerCustomer = findViewById(R.id.spinner_customer);
}
}


String.xml

<string-array name="spinner_category">
    <item>Male</item>
    <item>Female</item>
</string-array>


acitivty_add_customer.xml

 <Spinner
    android:id="@+id/spinner_customer"
    android:layout_width="match_parent"
    android:layout_height="30dp"
    android:layout_margin="10dp"/>


我没有使用数据库从spinner获取值。我正在使用字符串数组获取值。我想要它在String中的值。

最佳答案

您需要实现AdapterView.OnItemSelectedListener接口
之后,您可以通过onItemSelected()方法打印值。

样例代码:

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
    Spinner spinner;
    String[] sampleData = {
            "first",
            "second",
            "third",
            "fourth",
            "fifth"
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        spinner = findViewById(R.id.spinner);

        spinner.setOnItemSelectedListener(this);
        ArrayAdapter aa = new ArrayAdapter(this, android.R.layout.simple_spinner_item, sampleData);
        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(aa);
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        Toast.makeText(getApplicationContext(), sampleData[i], Toast.LENGTH_LONG).show();
    }

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

    }
}

关于java - 如何从微调器中获取值(value),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47906159/

10-12 04:11