Wednesday, September 17, 2014

Android 키보드 입력 IME 예제

EditBox 없이 키보드 입력을 받아서 IME를 제작하는 예제

package com.example.keyboardsample;

import android.content.Context;
import android.text.Editable;
import android.text.InputType;
import android.text.SpannableStringBuilder;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.BaseInputConnection;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;

public class WordComposer extends View {
 private EditableInputConnection mEii;

 public WordComposer(Context context) {
  super(context);
  // TODO Auto-generated constructor stub
  setFocusableInTouchMode(true);
  setFocusable(true);
 }

 @Override
 public boolean onTouchEvent(MotionEvent event) {
  super.onTouchEvent(event);
  if (event.getAction() == MotionEvent.ACTION_UP) {

   InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
   imm.showSoftInput(this, InputMethodManager.SHOW_FORCED);
  }
  return true;
 }

 @Override
 public boolean onCheckIsTextEditor() {
  return true;
 }

 @Override
 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {

  outAttrs.actionLabel = null;
  outAttrs.label = "Composer Test";
  outAttrs.inputType = InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
  outAttrs.imeOptions = EditorInfo.IME_ACTION_DONE;
  if (mEii == null)
   mEii = new EditableInputConnection(this);
  return mEii;
 }

 public class EditableInputConnection extends BaseInputConnection {
  private final View mView;
  private SpannableStringBuilder mEditable;
  String mText = new String();

  public EditableInputConnection(View textview) {
   super(textview, true);
   mView = textview;
   mEditable = (SpannableStringBuilder) Editable.Factory.getInstance().newEditable("composer");
  }

  public Editable getEditable() {
   return mEditable;
  }

  /*이곳을 통해 영문입력을 전달 받으세요. for English*/
  @Override
  public boolean commitText(CharSequence text, int newCursorPosition) {
   Log.d("WordComposer", text.toString());
   return super.commitText(text, newCursorPosition);
  }

  /*이곳을 통해 한글 입력을 바로바로 전달 받으세요. for Multibyte code*/
  @Override
  public boolean setComposingText(CharSequence text, int newCursorPosition) {
   Log.d("WordComposer", text.toString());
   return super.setComposingText(text, newCursorPosition);
  }
 }
}

No comments:

Post a Comment