1. 程式人生 > >【SoftKeyboard研究系列】自己動手做最簡單的SoftKeyboard

【SoftKeyboard研究系列】自己動手做最簡單的SoftKeyboard

引言

研究SoftKeyboard也有一段時間了,鑑於目前關於輸入法的教程繁多,但又不能解決本人所有的困惑,故開始自己研究。經過一段時間的摸索,逐漸理清了整個框架結構。下面就從本人寫的一個最簡單的SimpleSoftKeyboard為例,來介紹怎麼實現一個自定義的SoftKeyboard。

這個SimpleSoftKeyboard雖然程式碼量不到50行,但也五臟俱全。

SimpleSoftKeyboard類

程式碼

下面直接上程式碼:

package com.example.simplesoftkeyboard;

import android.inputmethodservice.InputMethodService;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;

public class SimpleSoftKeyboard extends InputMethodService {
	
	private InputMethodManager mInputMethodManager;
	
	private InputConnection mInputConnection;
	
	private View mInputView;
	
	@Override
	public void onCreate() {
		super.onCreate();
		mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
	}
	
	@Override
	public View onCreateInputView() {
		mInputConnection = getCurrentInputConnection();
		
		mInputView = getLayoutInflater().inflate(R.layout.input, null);
		Button button1 = (Button) mInputView.findViewById(R.id.button1);
		Button button2 = (Button) mInputView.findViewById(R.id.button2);
		OnClickListener onClickListener = new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(v.getClass() == Button.class) {
					mInputConnection.commitText(((Button) v).getText(), 1);
				}
			}
			
		};
		button1.setClickable(true);
		button2.setClickable(true);
		button1.setOnClickListener(onClickListener);
		button2.setOnClickListener(onClickListener);
		return mInputView;
	}
	
}
整個應用就只有這一個類,但已足夠實現我們想要的簡單功能。

效果圖

下面上效果圖:



因為只是簡單演示,只放上了兩個按鈕。

SimpleSoftKeyboard類解釋說明