2012-10-28 43 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));     
}