2011-12-27 2 views
0

다음 app에 textview 및 edittext가 있습니다. edittext 값이 변경되면 textview의 내용이 업데이트됩니다. 이제 값을 정수로 받아야합니다.
안드로이드 EditText 10 진수 정수 값

package your.test.two; 

import android.app.Activity; 
import android.os.Bundle; 
import android.text.Editable; 
import android.text.TextWatcher; 
import android.widget.EditText; 
import android.widget.TextView; 

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 input = (EditText)findViewById(R.id.editText1); 
    input.addTextChangedListener(new TextWatcher(){ 
     public void afterTextChanged(Editable s){ 
      update(); 
     } 
     public void beforeTextChanged(CharSequence s, int start, int count, int after){} 
     public void onTextChanged(CharSequence s, int start, int before, int count){} 
    }); 
} 

public void update(){ 
    EditText source = (EditText)findViewById(R.id.editText1); 
    Editable sourceData = source.getText(); 
    TextView destination = (TextView)findViewById(R.id.textView1); 
    destination.setText(sourceData); 
} 
} 


은 지금 그것에 if 문 제가 할 수 있도록 다음과 같이 sourceData 편집은 어떻게 든 정수로 변환하려면 : 이것은 현재의 응용 프로그램입니다

if(sourceData>255){ 
    sourceData = 0; 
} 

editText1에 다음 줄을 추가하여 main.xml의 edittext 값을 이미 변경했습니다.

android:inputType="number" 
android:maxLength="3" 
android:numeric="integer" 

누군가가 제게이 일을 어떻게 할 수 있는지에 대한 몇 가지 지침을 줄 수 있습니까? 그것을 인터넷 검색을하지만 모두가 내가 끝낼 된 것은 같은 것들이다 :

Integer i = Integer.parseInt(edittext.gettext().tostring()); 

&

Integer i = Integer.valueOf(String s); 

그리고 나는 확실히 그 작동하거나 이해하지 않습니다. 도와주세요!? :

답변

2

당신은, 당신은 정수를 설정하려는 변수로 난을 대체함으로써

Integer i = Integer.parseInt(edittext.gettext().tostring()); 

을 사용할 수 있어야합니다을 귀하의 사례 "sourceData"및

public void update(){ 
    EditText source = (EditText)findViewById(R.id.editText1); 
    Integer sourceData = Integer.parseInt(source.getText().toString()); 
    TextView destination = (TextView)findViewById(R.id.textView1); 
    destination.setText(Integer.toString(sourceData)); 
} 
} 
+0

아아 고맙습니다. 그 약간의 코드가 제가 찾고있는 코드였습니다! destination.setText (Integer.toString (sourceData)); 정말 도움이되었습니다. 고맙습니다! – Anomaly

1

EditText의 XML 속성을 숫자로 설정할 수 있지만 사용자가 숫자가 아닌 다른 정보를 입력하지 못하도록합니다. EditText의 텍스트는 항상 String입니다. 그럼에도 불구하고, 당신은 정수로 변환 할 수 있습니다 다음 실행 조건 :

public void update() { 
    EditText source = (EditText)findViewById(R.id.editText1); 
    int sourceData = Integer.valueOf(source.getText().toString()); 

    if (sourceData > 255) { 
     sourceData = 0; 
    } 

    TextView destination = (TextView)findViewById(R.id.textView1); 
    destination.setText(Integer.toString(sourceData)); 
} 
+0

아악 고맙습니다들 :

그래서 당신이 뭔가를 얻을 것이라고 당신 글고 상자의 이름으로 글고 치기를 교체, 그래서 '소스'! 그 약간의 코드가 제가 찾고있는 코드였습니다! destination.setText (Integer.toString (sourceData)); 정말 도움이되었습니다. 고맙습니다! – Anomaly