2016-09-29 51 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

就是这样!非常感谢! –