2016-09-29 53 views
2

我正在嘗試使微調框將在每次選擇列表中的項目時顯示不同的文本視圖。當我運行我的代碼時,我可以在不同的項目之間切換,但文本不會根據選擇進行更新。我已經看過各種類似的問題,但他們的解決方案都沒有做到我所期待的。如何讓微調框顯示文本視圖

下面是主要的活動我的代碼:

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) { 

} 

}

任何提示將apprieated,因爲這是我第一次在機器人工作室編碼和它採取的一點點時間來獲得習慣於。

+0

正確的方法是使用XML文件填充微調器。然後你的字符串值被保存在那裏,並可以使用選定的索引進行訪問。 – durbnpoisn

+0

你添加了spinner.setOnItemSelectedListener(this);在你的代碼? – Exigente05

回答

0

從您的代碼發佈的方式來看,您的偵聽器看起來沒有連接到微調器。請致電spinner.setOnItemSelectedListener(new listener)spinner.setOnItemSelectedListener(this)

+0

就是這樣!非常感謝! –