简体   繁体   中英

Spinner text not showing the default value, nor the selected value

The options for the spinner are only visible when I hit the spinner arrow. However, the default text and the selected text fail to show.

This is the xml for the spinner :

<Spinner
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:id="@+id/spinner1"
    android:ems="10"
    android:textColor = "#000000"
    android:layout_alignTop="@+id/roleNameTag"
    android:layout_alignStart="@+id/insertPass" />

This is the java code :

public class LoginActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

ArrayAdapter<CharSequence> adapter;
Spinner spinner;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login_page);

    spinner = (Spinner)findViewById(R.id.spinner1);
    /*ArrayAdapter<String> adapter = new ArrayAdapter<String>(LoginActivity.this,
            android.R.layout.simple_spinner_item,R.id.spinner1); */


    adapter = ArrayAdapter.createFromResource(getApplicationContext(),
            R.array.atco_array, android.R.layout.simple_spinner_item);

    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(this);
    spinner.setSelection(0,true); //set the default value
}
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
    // An item was selected. You can retrieve the selected item using
    // parent.getItemAtPosition(pos)

    //here however, we just set the spinner value to the one selected
    String text = spinner.getSelectedItem().toString();
    int spinnerPosition = adapter.getPosition(text);
    spinner.setSelection(spinnerPosition);
    }

@Override
public void onNothingSelected(AdapterView<?> parent) {
    // Another interface callback
    spinner.setSelection(0,true); //set the default value
}
}

And this is what I have tried :

Spinner control not showing the selected text

Android: setSelection having no effect on Spinner

These were the only relevant ones I found.

I set the text color to black. Set the default value , both right after setAdapter in onCreate and in the onNothingSelected methods , still nothing. Included the "true" boolean in the setSelection function.

Android API v21

Help ?

adapter = new ArrayAdapter<String>(LoginActivity.this, android.R.layout.simple_spinner_item, atco_array);

You not added any data into adapter to show in Spinner, so that is occurs. Set Data into adapter before call setSelection(0,true) , it might be help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM