2012-06-05 2 views
0

String.xmlмножительной 2 значения Горячо вместе

<string-array name="fruits"> 
     <item>Apple</item> 
     <item>Banana</item> 
     <item>Orange</item> 
     <item>Pear</item> 
     <item>Watermelon</item> 
     <item>Mango</item> 
     <item>Pineapple</item> 
     <item>Strawberry</item> 
</string-array> 

<string-array name="total"> 
    <item>1</item> 
    <item>2</item> 
    <item>3</item> 
    <item>4</item> 
    <item>5</item> 
    <item>6</item> 
    <item>7</item> 
    <item>8</item> 
</string-array> 

<string-array name="calorie"> 
    <item>80</item> 
    <item>101</item> 
    <item>71</item> 
    <item>100</item> 
    <item>45</item> 
    <item>135</item> 
    <item>80</item> 
    <item>53</item> 
</string-array>  

Java файл:

public class Fruit extends Activity implements OnClickListener, OnItemSelectedListener { 
private TextView tvFruit, tvNo; 
Context context=this; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.fruit); 

    tvFruit = (TextView) findViewById(R.id.tvfruit); 
    tvNo = (TextView) findViewById(R.id.tvno); 


    final Spinner fruits = (Spinner)findViewById(R.id.spin_fruit); 
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
      this,R.array.fruits,android.R.layout.simple_spinner_item); 
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    fruits.setAdapter(adapter); 
    fruits.setOnItemSelectedListener(this); 

    fruits.setOnItemSelectedListener(new OnItemSelectedListener(){ 
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, 
    long arg3) { 
      // TODO Auto-generated method stub 
      String selectedItem = fruits.getSelectedItem().toString(); 
      tvFruit.setText(selectedItem); 
     } 

    public void onNothingSelected(AdapterView<?> arg0) { 
     // TODO Auto-generated method stub 

    } 

    }); 

    final Spinner num = (Spinner)findViewById(R.id.spin_no); 
    ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(
      this,R.array.total,android.R.layout.simple_spinner_item); 
    adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    num.setAdapter(adapter1); 
    num.setOnItemSelectedListener(this); 

    num.setOnItemSelectedListener(new OnItemSelectedListener(){ 
     public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, 
     long arg3) { 
       // TODO Auto-generated method stub 
       String selectedItem = num.getSelectedItem().toString(); 
       tvNo.setText(selectedItem); 
      } 

     public void onNothingSelected(AdapterView<?> arg0) { 
      // TODO Auto-generated method stub 

     } 

     }); 

    Button save = (Button) findViewById(R.id.bsave); 
    save.setTextColor(Color.BLUE); 
    save.setOnClickListener(new View.OnClickListener() { 


      public void onClick(View arg0) { 
       // TODO Auto-generated method stub 
       // Get the subject details and show it in an alertdialog 
       AlertDialog.Builder builder = new AlertDialog.Builder(context); 
       builder.setMessage("Success"); 
       builder.setPositiveButton("OK", null); 
       builder.setNegativeButton("View Log", new DialogInterface.OnClickListener(){ 

        public void onClick(DialogInterface dialog, int which) { // this part is done for the negative button 
                      // if we want it to link to new intent 
         launchIntent(); 
        } 

       }); 
       builder.create().show(); 
      } 

      //making the "View Log" button in dialog box to go to new intent FruitLog.class 
      private void launchIntent(){ 
       Intent i = new Intent(Fruit.this, FruitLog.class); 
       i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
       startActivity(i); 
      } 


     }); 

    } 

so when user click 3 bananas in spinner, i want to know how to do the code for multiplication of calories. once done with the calculation, it should show 303 calories in the "total calorie" textview

поэтому, когда пользователь нажмет 3 банана в блесны, я хочу знать, как сделать код для умножения калорий. после выполнения расчета, он должен показать 303 калории в тексте «полная калория»

Может ли кто-нибудь мне посоветовать, как сделать кодирование для расчета. например, помогите мне с 2 яблочными калориями, а остальное я постараюсь выяснить, почему. это сообщество очень полезно.

ответ

1

Используя существующий код, я хотел бы попробовать что-то вдоль линии это:

Во-первых, изменить calorie массив на integer-array. Затем добавьте:

public int calculateCalories() { 
    int[] calorie = getResources().getIntArray(R.array.calorie); 
    return Integer.parseInt((String) num.getSelectedItem()) * calorie[fruits.getSelectedItemPosition()]; 
} 

Эта функция должна возвращать количество выбранных фруктов, умноженное на его калорийность. Для того, чтобы быть явным вы установите это непосредственно в TextView так:

totalTextView.setText(String.valueOf(calculateCalories())); 

Вы должны будете сделать num и fruits видны всему классу, объявляя их точно так же tvFruit объявлен.

+0

И что будет, когда пользователь выбирает первую позицию для количества 'Spinner' с вашим кодом? – Luksprog

+0

@Luksprog Иногда мне хотелось бы, чтобы у SO был встроенный компилятор ... – Sam

+0

Вы разбираете (если я правильно понял ваш код) позицию, выбранную из количества 'Spinner', ** num **. Когда это будет соответствовать выбранной первой позиции, вы будете разбирать '0', поэтому общее значение суммы всегда будет' 0' для первой позиции количества. – Luksprog

Смежные вопросы