2011-12-27 19 views
5

Edittext'imin boş kalmamasını sağlamak için kullanmak istediğim aşağıdaki koda sahibim. Yani eğer ilk çizilmiş 0 (sıfır) odak değişiklikleri, İşte şimdiye kadar app olduğunda 0'a dönmek zorundadır kaldırılır:Edittext'in boş bırakılmasını önleme

package your.test.two; 

import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.EditText; 

public class TesttwoActivity extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     EditText edtxt = (EditText)findViewById(R.id.editText1); 
     // if I don't add the following the app crashes (obviously): 
     edtxt.setText("0"); 
     edtxt.setOnFocusChangeListener(new View.OnFocusChangeListener() { 

      public void onFocusChange(View v, boolean hasFocus) { 
       // TODO Auto-generated method stub 
       update(); 
      } 
     }); 
    } 

    public void update() { 
     EditText edittxt = (EditText)findViewById(R.id.editText1); 
     Integer i = Integer.parseInt(edittxt.getText().toString()); 
     // If i is an empty value, app crashes so if I erase the zero 
     //on the phone and change focus, the app crashes 
    } 
} 

ben güncellemede aşağıdaki denedim() yöntemi:

String str = edittxt.getText().toString(); 
if (str == "") { 
    edittxt.setText("0"); 
} 

Ama işe yaramıyor. Edittext'in hiçbir zaman emtilememesine nasıl izin verebilirim, boş olduğunda sıfır, ancak bir değer olduğunda sıfır değerine geri dönebilir. Edittext'in sadece sayısal değerlere izin verdiğinden emin oldum.

cevap

5
if(str.equals("")){ 
    edittxt.setText("0"); 
} 

WarrenFaith haklı. Bu sorun hakkında daha fazla bilgi edinmek için bu mesaja bakın: Java String.equals versus ==

+1

Çok teşekkür ederim! Bu çalıştı. – Anomaly

+0

Bu soruna rastlarsanız, 'equals()' ve '==' arasındaki farkları okumalısınız. @Christian: belki bir açıklama biraz daha iyi olurdu, çünkü bu sorun temelleri OP için belirsizdir. – WarrenFaith

0
Sana belirtmedi beri elimden (muhtemelen atılan hatadır bir NumberFormatException yakalar bir try/catch bloğu ile parseInt çağrısı çevreleyen öneriyoruz

sadece tahmin et), öyle görünüyor:

public void update() { 
    EditText edittxt = (EditText)findViewById(R.id.editText1); 
    Integer i; 
    try { 
     i = Integer.parseInt(edittxt.getText().toString()); 
     // do something with i 
    } catch (NumberFormatException e) { 
     // log and do something else like notify the user or set i to a default value 
    }  
}