Blog Archives

Detecting language change in keyboard for IOS

For detecting IOS keyboard language change when you are in textfield / textview, you can do it in
– (BOOL)textField:(UITextField *)textView shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)text

The following will detect Chinese character (in general) whenever text is input into the textfield.

// This will check if the current character user entered is not a chinese character
if([[UITextInputMode currentInputMode].primaryLanguage rangeOfString:@"zh-"].location != NSNotFound){
// Put your code here.
}
Advertisements

Check if virtual keyboard is up

As most of you can find in internet, there is no easy way to check if the soft keyboard is shown on the screen. Depending on what you are looking to achieve, for Touch Screen only application, I use the following solution. Might not be the perfect solution for you but it works for me.

As this is TOUCH only application, so I assume soft keyboard will only get triggered by when one of the edit text field got touch. So I set a public variable for the flag, false by default. When user click on either one of the edit text field, touch listener will set the flag to true, and when focused came back to main view, I will set the flag back to false in dispatchTouchEvent method.

Setting the flag

//This is my flag
public boolean isSoftKeyboardDisplayed = false;

Now, set listener for the edit text field

// This is my edit text field box
EditText editText = (EditText)findViewById(R.id.edittext);
editText.setOnTouchListener(new onTouchListener(){
@Override
public void onTouch(View v, MotionEvent event){
// The flag is set to true everytime the edit text is touched.
isSoftKeyboardDisplayed = true;
}
});

Dismiss the soft keyboard by implementing  dispatchTouchEvent to your root view. So when user touch any where other than the edit text field, the soft keyboard dissapear

// This part is to dismiss the softkeyboard when you click anywhere other than the edit text
@Override
public boolean dispatchTouchEvent(MotionEvent event) {

View v = getCurrentFocus();
boolean ret = super.dispatchTouchEvent(event);
if (v instanceof EditText) {
View w = getCurrentFocus();
int scrcoords[] = new int[2];
w.getLocationOnScreen(scrcoords);
float x = event.getRawX() + w.getLeft() - scrcoords[0];
float y = event.getRawY() + w.getTop() - scrcoords[1];
if (event.getAction() == MotionEvent.ACTION_UP && (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w.getBottom()) ) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
// This is where I set the flag back to false when my soft keyboard is hidden
isSoftKeyboardDisplayed= false;
}
}
return ret;
}

As a result, I just check the isSoftKeyboardDisplayed flag for my keyboard display check.