2012年10月30日火曜日

[Android]Software KeyboardをActivityに配置する

android-sdkにSoftKeyboardというソフトキーボードのサンプルがあったので見てみました。キーボードアプリを作るのは大変そうだけど、仕組みは単純で、基本的にServiceからKeyboardViewというビューを作り画面に表示するだけです。
このKeyboardViewはViewを継承して作られてるクラスなので、普通にActivity上に配置出来るよね?と思いやってみました。結果、KeyboardViewを作成して配置するだけで動きました。
Keyboard keyboard = new Keyboard(this, R.xml.qwerty);
KeyboardView keyboardView = new KeyboardView(this,null);
keyboardView.setKeyboard(keyboard);
keyboardView.setOnKeyboardActionListener(this);
layout.addView(keyboardView);
1行目、xmlで定義したキーボードの配列を作ります。↓sdkのサンプルのを抜粋
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
android:horizontalGap="0px"
android:verticalGap="0px"
android:keyHeight="55dip"
>
<Row>
<Key android:codes="113" android:keyLabel="q" android:keyEdgeFlags="left"/>
<Key android:codes="119" android:keyLabel="w"/>
<Key android:codes="101" android:keyLabel="e" />
<Key android:codes="114" android:keyLabel="r"/>
<Key android:codes="116" android:keyLabel="t"/>
<Key android:codes="121" android:keyLabel="y"/>
<Key android:codes="117" android:keyLabel="u"/>
<Key android:codes="105" android:keyLabel="i"/>
<Key android:codes="111" android:keyLabel="o"/>
<Key android:codes="112" android:keyLabel="p" android:keyEdgeFlags="right"/>
</Row>
2行目と3行目でKeyboardViewクラスを作り、上で作ったKeyboardを設定します。4行目でリスナーを設定して、キーが押された時、などのイベントを取得出来ます。
public class Main extends Activity implements KeyboardView.OnKeyboardActionListener {
Activityにインターフェースを設定して、10個近いメソッドを実装しました。キーボード入力を受け取るonKeyの例
public void onKey(int primaryCode, int[] keyCodes) {
if(primaryCode == Keyboard.KEYCODE_DELETE ){
string.deleteCharAt(string.length()-1);
}else{
string.append((char)primaryCode);
}
tv.setText(string);
}
これだけでActivityにキーボードを表示し、TextViewに対して文字入力が出来るようになりました。Androidの実装って素晴らしいです。

高機能なViewなので、キーボード以外にも使い道がありそうですね。Androidのソフトキーボードはユーザーが自由に選択出来るので素敵ですが、その分アプリからのハンドリングは難しいです。キーボード自体を自前で持ってしまうのもありかも。

0 件のコメント:

コメントを投稿