2012-10-28 44 views
0

我是新的android開發.. 我有這樣的代碼在我的主類:Android - 如何增加EditText值?

Button prevBtn, pauseBtn, nextBtn; 
EditText counterTxt; 

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

     SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); 

     prevBtn = (Button)findViewById(R.id.prevBtn); 
     pauseBtn = (Button)findViewById(R.id.pauseBtn); 
     nextBtn = (Button)findViewById(R.id.nextBtn);   
     counterTxt = (EditText)findViewById(R.id.counterTxt); 

     prevBtn.setOnClickListener(new View.OnClickListener() {   
      int t = Integer.parseInt(counterTxt.getText().toString());  

      public void onClick(View v) { 
       counterTxt.setText(String.valueOf(t-1));     
      }  

     }); 


     nextBtn.setOnClickListener(new View.OnClickListener() {   
      int t = Integer.parseInt(counterTxt.getText().toString()); 

      public void onClick(View v) { 
       counterTxt.setText(String.valueOf(t+1));     
      }  

     });  



} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.activity_affirmations, menu); 
    return true; 
} 

當我點擊「上一步」,則文本字段值變爲19

當我點擊「下一步「,文本字段值將變爲21.

但它只顯示這兩個值,沒有別的,無論我再次單擊。我想減去或加1,只要我點擊相應的按鈕。

我認爲這是因爲事件監聽器在onCreate()方法內?每次點擊時如何更新它的想法?

enter image description here

回答

6

您需要將您的parseInt裏面你onClick

nextBtn.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View v) { 
      int t = Integer.parseInt(counterTxt.getText().toString()); 
      counterTxt.setText(String.valueOf(t+1));     
     }  

    });  
+0

謝謝你,我不能相信我沒有」看到這個:)這是因爲Android開發(和Java)仍然讓我困惑。非常感謝@Ralgha :) –

1

在兩種情況下,t被定義爲收聽者的成員變量,並沒有改變。移動它的onClick方法裏面,而不是像這樣(在兩種情況下):

public void onClick(View v) { 
    int t = Integer.parseInt(counterTxt.getText().toString()); 
    counterTxt.setText(String.valueOf(t-1));     
}