我想创建一个应用程序,其中我有2个按钮和1个edittext。按钮是+和 - 。当我点击+按钮时,我应该在edittext中获得计数器++,当我点击 - 按钮时,计数器 - 发生并在编辑文本中写入。 现在当我点击计数器 - 当编辑文本中的默认数字为0时,它会像-1,-2,-3等...但我不想把数字小于0。那么应该添加什么以下代码。
代码。
public class MainActivity extends Activity implements OnClickListener
{
int counter=0;
EditText et1;
Button btnminus,btnplus;
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1 = (EditText) findViewById(R.id.et_number);
btnminus = (Button) findViewById(R.id.btn_minus);
btnplus = (Button) findViewById(R.id.btn_plus);
btnminus.setOnClickListener(this);
btnplus.setOnClickListener(this);
}
public void onClick(View v)
{
if(v == btnminus)
{
counter--;
et1.setText(Integer.toString(counter));
}
if(v == btnplus)
{
counter++;
et1.setText(Integer.toString(counter));
}
}
}
答案 0 :(得分:0)
if(v == btnminus && counter!=0)
{
counter--;
et1.setText(Integer.toString(counter));
}
答案 1 :(得分:0)
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1 = (EditText) findViewById(R.id.et_number);
btnminus = (Button) findViewById(R.id.btn_minus);
btnplus = (Button) findViewById(R.id.btn_plus);
et1.setText(Integer.toString(counter));
btnminus.setOnClickListener(this);
btnplus.setOnClickListener(this);
}
public void onClick(View v)
{
if(v == btnminus)
{
int check=Integer.valueOf(et1.getText().toString);
if(check!=0){
counter--;
et1.setText(Integer.toString(counter));
}
}
if(v == btnplus)
{
counter++;
et1.setText(Integer.toString(counter));
}
}
答案 2 :(得分:0)
if(v == btnminus && counter>0) // if counter at least ==1 it could be decremented
et1.setText(String.valueOf(--counter)); //prefix decrement
else if(v == btnplus) // else if wont be checked if v == btnminus but counter is 0
et1.setText(String.valueOf(++counter)); // prefix inscrement