2017-01-04 2 views
1

나는 EditText가 있으며 사용자가 시간을 hh:mm 형식으로 입력해야한다고 가정합니다. 사용자가 시간을 입력하면 세미콜론을 편집 텍스트에 자동으로 추가하려고합니다. 편집 텍스트가 두 개의 숫자로 구성되어 있는지 확인하는 onKeyDown 메소드와 같은 것으로 생각됩니다.이 경우 세미콜론을 추가하십시오. 이것이 가능한가? 그렇다면 어떻게?Android 스튜디오에서 텍스트를 편집하여 키를 눌렀을 때

+0

의 사용 가능한 복제 (http://stackoverflow.com/questions/8543449/how-to-use- the-textwatcher-class-in-android) –

답변

2

정확하게 필요한 것을 수행하는 TextWatcher을 사용해야합니다. 기본적으로 3 가지 방법이 있습니다 : beforeTextChanged(), onTextChanged(), afterTextChanged().

처음 두 개의 메서드는 EditText 내부의 텍스트를 변경하는 데 사용되지 않고 텍스트 변경 내용을 추적하는 데 사용됩니다. 마지막 하나 인은 텍스트를 수정하고 스타일을 지정할 수있는 방법입니다. 코드는 다음과 같을 것이다 : [? 안드로이드에 TextWatcher 클래스를 사용하는 방법]

String text = ""; 

yourEditText.addTextChangedListener(new TextWatcher() { 
     @Override 
     public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { 

     } 

     @Override 
     public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { 

     } 

     @Override 
     public void afterTextChanged(Editable editable) { 

      // work with editable here and add : 

      String newValue = editable.toString(); 

      if (newValue.length() > text.length()) { 
       text = editable.toString(); 
       if (text.length() == 2) { 
        yourEditText.setText(text + ":"); 
       } 
      } 
      else if (newValue.length() < text.length()) { 
       text = editable.toString(); 
      } 
     } 
    }); 
+0

큰 활약을했습니다. "13시 30 분"을 입력하고 그것을 삭제하려면 세미콜론을 삭제할 때 텍스트가 변경된 후 두 개의 숫자가 있기 때문에 세미콜론을 다시 인쇄합니다. 나는 이것을 찾으려고했지만 아무 것도 찾지 못했다. if (keyCode! = KeyEvent.KEYCODE_DEL) –

+0

@SimonAndersson 나는 내 대답을 업데이트했다. 그것을 신중히 들여다 보아라. – Marat

2
editText.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() == 2) 
    editText.setText(S+":"); 
    if(s.length() == 5) //(hh:mm) length is 5 
    editText.setEnabled(false); //it accept only 5 char. 
} 
}); 
관련 문제