Search code examples
androidandroid-event

How to get a spinner to display textview


I am trying to make a spinner that will display a different text view each time an item from the list has been selected. When I run my code, I am able to switch between the different items, but the text is not updating based on the selection. I have looked at a variety of similar questions but none of their solutions have done what I am looking for.

Here is my code from the main activity:

Spinner spinner;
TextView example;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    example = (TextView) findViewById(R.id.example);
    spinner = (Spinner) findViewById(R.id.spinner);

    ArrayAdapter adapter=ArrayAdapter.createFromResource(this, R.array.medication_array,android.R.layout.simple_spinner_item);
    spinner.setAdapter(adapter);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}


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

            switch(position)
            {
                case 0:
                    example.setText("Depression");
                    break;
                case 1:
                    example.setText(R.string.ssriexample);
                    break;
                case 2:
                    example.setText(R.string.snriexample);
                    break;
                case 3:
                    example.setText(R.string.tcaexample);
                    break;
                case 4:
                    example.setText(R.string.moiexample);
                    break;
                case 5:
                    example.setText(R.string.otherexample);
                    break;

            }

}

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

}

}

Any tips would be apprieated as this is my first time coding in android studios and it's taking a little bit of time to get used to.


Solution

  • From the way your code is posted, it looks like your listeners are not attached to the spinner. Call spinner.setOnItemSelectedListener(new listener) or spinner.setOnItemSelectedListener(this)