2014-09-19 42 views
0

我想要製作一個應用程序來跟蹤出席率。爲此,我使用數字選擇器。操縱兩個Numberpickers的值Android

下面的代碼

import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnLongClickListener; 
import android.widget.EditText; 
import android.widget.NumberPicker; 
import android.widget.NumberPicker.OnValueChangeListener; 
import android.widget.TextView; 

public class MainActivity extends Activity { 

NumberPicker np1,np2; 
TextView tv1,tv3,tv2; 
EditText et1; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 


    np1 = (NumberPicker) findViewById(R.id.numberPicker1); 
    np2 = (NumberPicker) findViewById(R.id.numberPicker2); 
    et1 = (EditText) findViewById(R.id.editText1); 
    tv1 = (TextView) findViewById(R.id.textView1); 
    tv2 = (TextView) findViewById(R.id.textView2); 
    tv3 = (TextView) findViewById(R.id.textView3); 


    np1.setMinValue(0); 
    np1.setMaxValue(50); 
    np1.setWrapSelectorWheel(true); 
    np2.setMinValue(0); 
    np2.setMaxValue(50); 
    np2.setWrapSelectorWheel(true); 

    np1.setOnValueChangedListener(new OnValueChangeListener() { 

    @Override 
    public void onValueChange(NumberPicker picker, int oldValb, int newValb) { 

     tv3.setText("Bunked Lecs "+ newValb); 

    } 

}); 

    np2.setOnValueChangedListener(new OnValueChangeListener() { 

     @Override 
     public void onValueChange(NumberPicker picker, int oldValt, int newValt) { 

      tv2.setText("Total Lecs "+ newValt); 


     } 
    }); 

    tv1.setOnLongClickListener(new OnLongClickListener() { 

     public boolean onLongClick(View v) { 
      tv1.setVisibility(4); 
      final EditText et1=(EditText)findViewById(R.id.editText1); 
      et1.setVisibility(1);      
      return false; 

     } 
    }); 
} 
} 

我需要做的就是計算和打印(1-newValb/newVal)每當用戶改變了多個選擇器的值。 我該如何做到這一點?

或者我應該做出什麼樣的變化在此代碼

+0

令人厭煩的答案是:在每個onValueChanged存儲中,成員變量中的新值是您的Activity,然後調用一個方法,該方法採用兩個值,計算新結果,然後將其寫入結果TextView。更有趣的答案是:看看rxjava - 對於這種事情非常酷...... – 2014-09-19 17:15:21

+0

你能舉個例子嗎? – user3813862 2014-09-19 17:43:41

回答

0

我認爲它甚至比我首先想到簡單:

public void updateResult() { 
    int newValb = np1.getValue(); 
    int newValt = np2.getValue(); 

    float result = 1 - newValb/newValt; 

    tv1.setText(String.valueOf(result)); 
} 

np1.setOnValueChangedListener(new OnValueChangeListener() { 

    @Override 
    public void onValueChange(NumberPicker picker, int oldValb, int newValb) { 
     updateResult(); 
    } 

}); 

np2.setOnValueChangedListener(new OnValueChangeListener() { 

    @Override 
    public void onValueChange(NumberPicker picker, int oldValt, int newValt) { 
     updateResult(); 
    } 
}); 

還是我完全誤解你?

+0

我想在np1和np2的valuechange上動態計算結果。它似乎是正確的,但我仍然試圖 – user3813862 2014-09-19 18:28:15