SoftKeyboard.java - android Git repositories

文章推薦指數: 80 %
投票人數:10人

Example of writing an input method for a soft keyboard. This code is ... We are now going to initialize our state based on the type of. android/platform/development/master/./samples/SoftKeyboard/src/com/example/android/softkeyboard/SoftKeyboard.javablob:b76005fbf3f058a25cff74a9bc02ef4ad4661006[file][log][blame]/**Copyright(C)2008-2009TheAndroidOpenSourceProject**LicensedundertheApacheLicense,Version2.0(the"License");*youmaynotusethisfileexceptincompliancewiththeLicense.*YoumayobtainacopyoftheLicenseat**http://www.apache.org/licenses/LICENSE-2.0**Unlessrequiredbyapplicablelaworagreedtoinwriting,software*distributedundertheLicenseisdistributedonan"ASIS"BASIS,*WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.*SeetheLicenseforthespecificlanguagegoverningpermissionsand*limitationsundertheLicense.*/packagecom.example.android.softkeyboard;importandroid.app.Dialog;importandroid.content.Context;importandroid.inputmethodservice.InputMethodService;importandroid.inputmethodservice.Keyboard;importandroid.inputmethodservice.KeyboardView;importandroid.os.Build;importandroid.os.IBinder;importandroid.text.InputType;importandroid.text.method.MetaKeyKeyListener;importandroid.view.Display;importandroid.view.KeyCharacterMap;importandroid.view.KeyEvent;importandroid.view.View;importandroid.view.Window;importandroid.view.WindowManager;importandroid.view.inputmethod.CompletionInfo;importandroid.view.inputmethod.EditorInfo;importandroid.view.inputmethod.InputConnection;importandroid.view.inputmethod.InputMethodManager;importandroid.view.inputmethod.InputMethodSubtype;importandroidx.annotation.NonNull;importjava.util.ArrayList;importjava.util.List;/***Exampleofwritinganinputmethodforasoftkeyboard.Thiscodeis*focusedonsimplicityovercompleteness,soitshouldinnowaybeconsidered*tobeacompletesoftkeyboardimplementation.Itspurposeistoprovide*abasicexampleforhowyouwouldgetstartedwritinganinputmethod,to*befleshedoutasappropriate.*/publicclassSoftKeyboardextendsInputMethodServiceimplementsKeyboardView.OnKeyboardActionListener{staticfinalbooleanDEBUG=false;/***Thisbooleanindicatestheoptionalexamplecodeforperforming*processingofhardkeysinadditiontoregulartextgeneration*fromon-screeninteraction.Itwouldbeusedforinputmethodsthat*performlanguagetranslations(suchasconvertingtextenteredon*aQWERTYkeyboardtoChinese),butmaynotbeusedforinputmethods*thatareprimarilyintendedtobeusedforon-screentextentry.*/staticfinalbooleanPROCESS_HARD_KEYS=true;privateInputMethodManagermInputMethodManager;privateLatinKeyboardViewmInputView;privateCandidateViewmCandidateView;privateCompletionInfo[]mCompletions;privateStringBuildermComposing=newStringBuilder();privatebooleanmPredictionOn;privatebooleanmCompletionOn;privateintmLastDisplayWidth;privatebooleanmCapsLock;privatelongmLastShiftTime;privatelongmMetaState;privateLatinKeyboardmSymbolsKeyboard;privateLatinKeyboardmSymbolsShiftedKeyboard;privateLatinKeyboardmQwertyKeyboard;privateLatinKeyboardmCurKeyboard;privateStringmWordSeparators;/***Maininitializationoftheinputmethodcomponent.Besuretocall*tosuperclass.*/@OverridepublicvoidonCreate(){super.onCreate();mInputMethodManager=(InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);mWordSeparators=getResources().getString(R.string.word_separators);}/***Createnewcontextobjectwhoseresourcesareadjustedtomatchthemetricsofthedisplay*whichismanagedbyWindowManager.**@see{@linkContext#createDisplayContext(Display)}*/@NonNullContextgetDisplayContext(){if(Build.VERSION.SDK_INT0&&(newSelStart!=candidatesEnd||newSelEnd!=candidatesEnd)){mComposing.setLength(0);updateCandidates();InputConnectionic=getCurrentInputConnection();if(ic!=null){ic.finishComposingText();}}}/***Thistellsusaboutcompletionsthattheeditorhasdeterminedbased*onthecurrenttextinit.Wewanttousethisinfullscreenmode*toshowthecompletionsourself,sincetheeditorcannotbeseen*inthatsituation.*/@OverridepublicvoidonDisplayCompletions(CompletionInfo[]completions){if(mCompletionOn){mCompletions=completions;if(completions==null){setSuggestions(null,false,false);return;}ListstringList=newArrayList();for(inti=0;i0){characcent=mComposing.charAt(mComposing.length()-1);intcomposed=KeyEvent.getDeadChar(accent,c);if(composed!=0){c=composed;mComposing.setLength(mComposing.length()-1);}}onKey(c,null);returntrue;}/***Usethistomonitorkeyeventsbeingdeliveredtotheapplication.*Wegetfirstcrackatthem,andcaneitherresumethemorletthem*continuetotheapp.*/@OverridepublicbooleanonKeyDown(intkeyCode,KeyEventevent){switch(keyCode){caseKeyEvent.KEYCODE_BACK://TheInputMethodServicealreadytakescareoftheback//keyforus,todismisstheinputmethodifitisshown.//However,ourkeyboardcouldbeshowingapop-upwindow//thatbackshoulddismiss,sowefirstallowittodothat.if(event.getRepeatCount()==0&&mInputView!=null){if(mInputView.handleBack()){returntrue;}}break;caseKeyEvent.KEYCODE_DEL://Specialhandlingofthedeletekey:ifwecurrentlyare//composingtextfortheuser,wewanttomodifythatinstead//oflettheapplicationtothedeleteitself.if(mComposing.length()>0){onKey(Keyboard.KEYCODE_DELETE,null);returntrue;}break;caseKeyEvent.KEYCODE_ENTER://Lettheunderlyingtexteditoralwayshandlethese.returnfalse;default://Forallotherkeys,ifwewanttodotransformationson//textbeingenteredwithahardkeyboard,weneedtoprocess//itanddotheappropriateaction.if(PROCESS_HARD_KEYS){if(keyCode==KeyEvent.KEYCODE_SPACE&&(event.getMetaState()&KeyEvent.META_ALT_ON)!=0){//Asillyexample:inourinputmethod,Alt+Space//isashortcutfor'android'inlowercase.InputConnectionic=getCurrentInputConnection();if(ic!=null){//First,telltheeditorthatitisnolongerinthe//shiftstate,sinceweareconsumingthis.ic.clearMetaKeyStates(KeyEvent.META_ALT_ON);keyDownUp(KeyEvent.KEYCODE_A);keyDownUp(KeyEvent.KEYCODE_N);keyDownUp(KeyEvent.KEYCODE_D);keyDownUp(KeyEvent.KEYCODE_R);keyDownUp(KeyEvent.KEYCODE_O);keyDownUp(KeyEvent.KEYCODE_I);keyDownUp(KeyEvent.KEYCODE_D);//Andweconsumethisevent.returntrue;}}if(mPredictionOn&&translateKeyDown(keyCode,event)){returntrue;}}}returnsuper.onKeyDown(keyCode,event);}/***Usethistomonitorkeyeventsbeingdeliveredtotheapplication.*Wegetfirstcrackatthem,andcaneitherresumethemorletthem*continuetotheapp.*/@OverridepublicbooleanonKeyUp(intkeyCode,KeyEventevent){//Ifwewanttodotransformationsontextbeingenteredwithahard//keyboard,weneedtoprocesstheupeventstoupdatethemetakey//statewearetracking.if(PROCESS_HARD_KEYS){if(mPredictionOn){mMetaState=MetaKeyKeyListener.handleKeyUp(mMetaState,keyCode,event);}}returnsuper.onKeyUp(keyCode,event);}/***Helperfunctiontocommitanytextbeingcomposedintotheeditor.*/privatevoidcommitTyped(InputConnectioninputConnection){if(mComposing.length()>0){inputConnection.commitText(mComposing,mComposing.length());mComposing.setLength(0);updateCandidates();}}/***Helpertoupdatetheshiftstateofourkeyboardbasedontheinitial*editorstate.*/privatevoidupdateShiftKeyState(EditorInfoattr){if(attr!=null&&mInputView!=null&&mQwertyKeyboard==mInputView.getKeyboard()){intcaps=0;EditorInfoei=getCurrentInputEditorInfo();if(ei!=null&&ei.inputType!=InputType.TYPE_NULL){caps=getCurrentInputConnection().getCursorCapsMode(attr.inputType);}mInputView.setShifted(mCapsLock||caps!=0);}}/***Helpertodetermineifagivencharactercodeisalphabetic.*/privatebooleanisAlphabet(intcode){if(Character.isLetter(code)){returntrue;}else{returnfalse;}}/***Helpertosendakeydown/keyuppairtothecurrenteditor.*/privatevoidkeyDownUp(intkeyEventCode){getCurrentInputConnection().sendKeyEvent(newKeyEvent(KeyEvent.ACTION_DOWN,keyEventCode));getCurrentInputConnection().sendKeyEvent(newKeyEvent(KeyEvent.ACTION_UP,keyEventCode));}/***Helpertosendacharactertotheeditorasrawkeyevents.*/privatevoidsendKey(intkeyCode){switch(keyCode){case'\n':keyDownUp(KeyEvent.KEYCODE_ENTER);break;default:if(keyCode>='0'&&keyCode<='9'){keyDownUp(keyCode-'0'+KeyEvent.KEYCODE_0);}else{getCurrentInputConnection().commitText(String.valueOf((char)keyCode),1);}break;}}//ImplementationofKeyboardViewListenerpublicvoidonKey(intprimaryCode,int[]keyCodes){if(isWordSeparator(primaryCode)){//Handleseparatorif(mComposing.length()>0){commitTyped(getCurrentInputConnection());}sendKey(primaryCode);updateShiftKeyState(getCurrentInputEditorInfo());}elseif(primaryCode==Keyboard.KEYCODE_DELETE){handleBackspace();}elseif(primaryCode==Keyboard.KEYCODE_SHIFT){handleShift();}elseif(primaryCode==Keyboard.KEYCODE_CANCEL){handleClose();return;}elseif(primaryCode==LatinKeyboardView.KEYCODE_LANGUAGE_SWITCH){handleLanguageSwitch();return;}elseif(primaryCode==LatinKeyboardView.KEYCODE_OPTIONS){//Showamenuorsomethin'}elseif(primaryCode==Keyboard.KEYCODE_MODE_CHANGE&&mInputView!=null){Keyboardcurrent=mInputView.getKeyboard();if(current==mSymbolsKeyboard||current==mSymbolsShiftedKeyboard){setLatinKeyboard(mQwertyKeyboard);}else{setLatinKeyboard(mSymbolsKeyboard);mSymbolsKeyboard.setShifted(false);}}else{handleCharacter(primaryCode,keyCodes);}}publicvoidonText(CharSequencetext){InputConnectionic=getCurrentInputConnection();if(ic==null)return;ic.beginBatchEdit();if(mComposing.length()>0){commitTyped(ic);}ic.commitText(text,0);ic.endBatchEdit();updateShiftKeyState(getCurrentInputEditorInfo());}/***Updatethelistofavailablecandidatesfromthecurrentcomposing*text.Thiswillneedtobefilledinbyhoweveryouaredetermining*candidates.*/privatevoidupdateCandidates(){if(!mCompletionOn){if(mComposing.length()>0){ArrayListlist=newArrayList();list.add(mComposing.toString());setSuggestions(list,true,true);}else{setSuggestions(null,false,false);}}}publicvoidsetSuggestions(Listsuggestions,booleancompletions,booleantypedWordValid){if(suggestions!=null&&suggestions.size()>0){setCandidatesViewShown(true);}elseif(isExtractViewShown()){setCandidatesViewShown(true);}if(mCandidateView!=null){mCandidateView.setSuggestions(suggestions,completions,typedWordValid);}}privatevoidhandleBackspace(){finalintlength=mComposing.length();if(length>1){mComposing.delete(length-1,length);getCurrentInputConnection().setComposingText(mComposing,1);updateCandidates();}elseif(length>0){mComposing.setLength(0);getCurrentInputConnection().commitText("",0);updateCandidates();}else{keyDownUp(KeyEvent.KEYCODE_DEL);}updateShiftKeyState(getCurrentInputEditorInfo());}privatevoidhandleShift(){if(mInputView==null){return;}KeyboardcurrentKeyboard=mInputView.getKeyboard();if(mQwertyKeyboard==currentKeyboard){//AlphabetkeyboardcheckToggleCapsLock();mInputView.setShifted(mCapsLock||!mInputView.isShifted());}elseif(currentKeyboard==mSymbolsKeyboard){mSymbolsKeyboard.setShifted(true);setLatinKeyboard(mSymbolsShiftedKeyboard);mSymbolsShiftedKeyboard.setShifted(true);}elseif(currentKeyboard==mSymbolsShiftedKeyboard){mSymbolsShiftedKeyboard.setShifted(false);setLatinKeyboard(mSymbolsKeyboard);mSymbolsKeyboard.setShifted(false);}}privatevoidhandleCharacter(intprimaryCode,int[]keyCodes){if(isInputViewShown()){if(mInputView.isShifted()){primaryCode=Character.toUpperCase(primaryCode);}}if(isAlphabet(primaryCode)&&mPredictionOn){mComposing.append((char)primaryCode);getCurrentInputConnection().setComposingText(mComposing,1);updateShiftKeyState(getCurrentInputEditorInfo());updateCandidates();}else{getCurrentInputConnection().commitText(String.valueOf((char)primaryCode),1);}}privatevoidhandleClose(){commitTyped(getCurrentInputConnection());requestHideSelf(0);mInputView.closing();}privateIBindergetToken(){finalDialogdialog=getWindow();if(dialog==null){returnnull;}finalWindowwindow=dialog.getWindow();if(window==null){returnnull;}returnwindow.getAttributes().token;}privatevoidhandleLanguageSwitch(){mInputMethodManager.switchToNextInputMethod(getToken(),false/*onlyCurrentIme*/);}privatevoidcheckToggleCapsLock(){longnow=System.currentTimeMillis();if(mLastShiftTime+800>now){mCapsLock=!mCapsLock;mLastShiftTime=0;}else{mLastShiftTime=now;}}privateStringgetWordSeparators(){returnmWordSeparators;}publicbooleanisWordSeparator(intcode){Stringseparators=getWordSeparators();returnseparators.contains(String.valueOf((char)code));}publicvoidpickDefaultCandidate(){pickSuggestionManually(0);}publicvoidpickSuggestionManually(intindex){if(mCompletionOn&&mCompletions!=null&&index>=0&&index0){//Ifweweregeneratingcandidatesuggestionsforthecurrent//text,wewouldcommitoneofthemhere.Butforthissample,//wewilljustcommitthecurrenttext.commitTyped(getCurrentInputConnection());}}publicvoidswipeRight(){if(mCompletionOn){pickDefaultCandidate();}}publicvoidswipeLeft(){handleBackspace();}publicvoidswipeDown(){handleClose();}publicvoidswipeUp(){}publicvoidonPress(intprimaryCode){}publicvoidonRelease(intprimaryCode){}}



請為這篇文章評分?