我想在從我的微調框中選擇某個項目時在按鈕中顯示某個值。但它沒有做到這一點。請對我的值編碼一看:從按鈕中顯示的微調框中選擇的項目
public void onItemSelected(AdapterView<?> parent, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
selected = parent.getItemAtPosition(position).toString();
int index = parent.getSelectedItemPosition();
if(index == 0){
strCalories = "188 calories";
calories.setText(strCalories);
}
else if (index == 1){
strCalories = "185 calories";
calories.setText(strCalories);
}
else if (index == 2){
strCalories = "126 calories";
calories.setText(strCalories);
}
else if (index == 3){
strCalories = "149 calories";
calories.setText(strCalories);
}
else if (index == 4){
strCalories = "81 calories";
calories.setText(strCalories);
}
else if (index == 5){
strCalories = "66 calories";
calories.setText(strCalories);
}
else if (index == 6){
strCalories = "46 calories";
calories.setText(strCalories);
}
else if (index == 7){
strCalories = "89 calories";
calories.setText(strCalories);
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.btBreadWhiteSave:
String mealname = selected;
String servng = calories.getText().toString();
if ((mealname.isEmpty() || servng.isEmpty())){
// call for custom toast
viewErrorToast();
}
else {
boolean didItWork = true;
try{
BreakFastLog entry = new BreakFastLog(Bread_White.this);
entry.open();
entry.createEntry(mealname, servng);
entry.close();
}
catch(Exception e){
didItWork = false;
viewErrorToast();
}finally{
if (didItWork){
viewBMRSavedToast();
}
}
} // end of if else statement
break;
我的佈局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/ihealthfirst" >
<include
android:layout_width="fill_parent"
android:layout_height="match_parent"
layout="@layout/tabs_menu" />
<TextView
android:id="@+id/tvWhiteBread"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/whitebread"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Spinner
android:id="@+id/spWhiteBread"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:prompt="@string/white_bread_prompt"
android:entries="@array/white_bread_arrays" />
<TextView
android:id="@+id/btBreadWhiteCalories"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btBreadWhiteSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/save" />
</LinearLayout>
什麼我這裏缺少什麼?請幫我看看這裏出了什麼問題。謝謝。
你可以只使用'index'參數中提供的int position# – mango
你可以優化你的代碼,但它看起來很好......也許你的佈局有些錯誤?請張貼這個XML,以及如何定義「卡路里」。 – Sam
@Sam我的微調值列表來自字符串數組。 –