我是一个Android菜鸟,我正在尝试创建一个微调器,并希望更改另一个文本取决于微调器项目的选择。
例如,如果我选择果汁,我需要将文字改为"加仑。"等
这是我的代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
Button saveButton = (Button) findViewById(R.id.save_button);
Spinner foodSpinner = (Spinner) findViewById(R.id.foodSpinner);
String foodChoice = foodSpinner.getSelectedItem().toString();
TextView unit = (TextView) findViewById(R.id.units);
if(foodChoice.equals("Egg"))
{
unit.setText("Dozen");
}
else if(foodChoice.equals("Juice"))
{
unit.setText("gallons");
}
else if(foodChoice.equals("Carrot"))
{
unit.setText("bunch");
}
else if(foodChoice.equals("Chocolate"))
{
unit.setText("bars");
}
else if(foodChoice.equals("Bread"))
{
unit.setText("loaf");
}
saveButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(EditActivity.this,
MainActivity.class);
startActivity(intent);
}
});
}
但文字改为"数十"第一次,然后当我从微调器中选择其他项时它不会改变。
答案 0 :(得分:2)
将setOnItemSelectedListener
添加到Spinner以根据Spinner选择更改TextView文本:
foodSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String selItem = foodSpinner.getItemAtPosition(arg2).toString();
if(selItem.equals("Juice"))
{
unit.setText("gallons");
}....
}
});
答案 1 :(得分:0)
我在任何地方都看不到onItemSelectedListener。确保在微调器上设置一个。 foodSpinner.setOnItemSelectedListener(new onItemSelectedListener ...)
答案 2 :(得分:0)
添加项目选择的侦听器,如
sp.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
Toast.makeText(getBaseContext(), sp.getSelectedItem().toString(),
Toast.LENGTH_LONG).show(); }
}