2016-02-13 59 views
0

我有2個按鈕和1個數字段,如果我按下按鈕沒有東西在字段中,它崩潰,所以我想要做的是禁用按鈕,除非數字字段有一些東西,我已經四處尋找答案,但要麼他們不相關,或者我不知道它是如何適合我的代碼,這裏是每個按鈕的兩個onClick函數。由於如何禁用2個按鈕,如果一個數字字段爲空

public void toPounds(View view){ 
    EditText amount = (EditText)findViewById(R.id.amount); 

    Double omrAmount = Double.parseDouble(amount.getText().toString()); 

    Double gbrAmount = omrAmount * 1.79; 

    Toast.makeText(getApplicationContext(), "£" + gbrAmount.toString(), Toast.LENGTH_LONG).show(); 
} 

public void toRiyals(View view){ 
    EditText amount = (EditText)findViewById(R.id.amount); 

    Double gbrAmount = Double.parseDouble(amount.getText().toString()); 

    Double omrAmount = gbrAmount/1.79; 

    Toast.makeText(getApplicationContext(), omrAmount.toString() + " Riyals", Toast.LENGTH_LONG).show(); 
} 
+0

按下按鈕首先檢查號碼字段不爲空 –

回答

0
yourField.addTextChangedListener(new TextWatcher() { 

     @Override 
     public void afterTextChanged(Editable s) {} 

     @Override  
     public void beforeTextChanged(CharSequence s, int start, 
     int count, int after) { 
     } 

     @Override  
     public void onTextChanged(CharSequence s, int start, 
     int before, int count) { 
      if(s.length() == 0) 
      button1.setEnabled(false) 
     else 
     button1.setEnabled(true) 
     } 
     }); 

link

0

如果要禁用按鈕,如果編輯文本爲空,那麼你就可以做到以下幾點:

EditText amount = (EditText)findViewById(R.id.amount); 
Button button = (Button) findViewById(R.id.button1); 
if(amount.getText().toString().isEmpty()){ 
    button.setEnabled(false); 
} 

amount.addTextChangedListener(新TextWatcher(){

@Override 
    public void afterTextChanged(Editable s) {} 

    @Override  
    public void beforeTextChanged(CharSequence s, int start, 
    int count, int after) { 
    } 

    @Override  
    public void onTextChanged(CharSequence s, int start, 
    int before, int count) { 
     if(s.length() == 0) 
     button1.setEnabled(false) 
    else 
    button1.setEnabled(true) 
    } 
    }); 
0

不是專門針對您的問題的答案,但通常而言,您希望在調用現在會導致應用程序崩潰的代碼之前添加某種檢查。讓應用程序徘徊在周圍的代碼不是一個好主意。

也許做出這樣的方法:isMyEditTextValid(...){..}

相關問題