System keyboard. This answer tells how to make a custom system keyboard that can be used in any app that a user has installed on their phone.
Home
Public
Questions
Tags
Users
Collectives
ExploreCollectives
FindaJob
Jobs
Companies
Teams
StackOverflowforTeams
–Collaborateandshareknowledgewithaprivategroup.
CreateafreeTeam
WhatisTeams?
Teams
CreatefreeTeam
CollectivesonStackOverflow
Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost.
Learnmore
Teams
Q&Aforwork
Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch.
Learnmore
HowcanyoumakeacustomkeyboardinAndroid?
AskQuestion
Asked
9years,8monthsago
Active
1year,1monthago
Viewed
227ktimes
133
104
Iwanttomakeacustomkeyboard.Idon'tknowhowtodoitusingXMLandJava.ThefollowingpictureisamodelofthekeyboardIwanttomake.Itonlyneedsnumbers.
androidkeyboard
Share
Follow
editedJul6'19at13:03
DogLover
55811goldbadge55silverbadges1818bronzebadges
askedMar6'12at2:57
XX_brotherXX_brother
1,49744goldbadges1717silverbadges1515bronzebadges
3
6
[CreateYourOwnCustomKeyboardusingXMLLayoutsforAndroidDevices](tutorials-android.blogspot.com/2011/06/…)
– Jorgesys
Mar6'12at3:14
1
ThereisagoodtutorialatTuts:link
– HamedGhadirian
Nov11'15at20:21
Googlehasasample"SoftKeyboard"project,ortherearequitealotofresourceslinkedhere:customkeyboarddetails.blogspot.com/2019/02/…
– oliversisson
Feb1'19at20:00
Addacomment
|
9Answers
9
Active
Oldest
Votes
109
Systemkeyboard
Thisanswertellshowtomakeacustomsystemkeyboardthatcanbeusedinanyappthatauserhasinstalledontheirphone.Ifyouwanttomakeakeyboardthatwillonlybeusedwithinyourownapp,thenseemyotheranswer.
Theexamplebelowwilllooklikethis.Youcanmodifyitforanykeyboardlayout.
Thefollowingstepsshowhowtocreateaworkingcustomsystemkeyboard.AsmuchaspossibleItriedtoremoveanyunnecessarycode.Ifthereareotherfeaturesthatyouneed,Iprovidedlinkstomorehelpattheend.
1.StartanewAndroidproject
Inamedmyproject"CustomKeyboard".Callitwhateveryouwant.Thereisnothingelsespecialhere.IwilljustleavetheMainActivityand"HelloWorld!"layoutasitis.
2.Addthelayoutfiles
Addthefollowingtwofilestoyourapp'sres/layoutfolder:
keyboard_view.xml
key_preview.xml
keyboard_view.xml
Thisviewislikeacontainerthatwillholdourkeyboard.Inthisexamplethereisonlyonekeyboard,butyoucouldaddotherkeyboardsandswaptheminandoutofthisKeyboardView.
key_preview.xml
Thekeypreviewisalayoutthatpopsupwhenyoupressakeyboardkey.Itjustshowswhatkeyyouarepressing(incaseyourbig,fatfingersarecoveringit).Thisisn'tamultiplechoicepopup.ForthatyoushouldcheckouttheCandidatesview.
3.Addsupportingxmlfiles
Createanxmlfolderinyourresfolder.(RightclickresandchooseNew>Directory.)
Thenaddthefollowingtwoxmlfilestoit.(RightclickthexmlfolderandchooseNew>XMLresourcefile.)
number_pad.xml
method.xml
number_pad.xml
Thisiswhereitstartstogetmoreinteresting.ThisKeyboarddefinesthelayoutofthekeys.
Herearesomethingstonote:
keyWidth:Thisisthedefaultwidthofeachkey.The20%pmeansthateachkeyshouldtakeup20%ofthewidthoftheparent.Itcanbeoverriddenbyindividualkeys,though,asyoucanseehappenedwiththeDeleteandEnterkeysinthethirdrow.
keyHeight:Itishardcodedhere,butyoucouldusesomethinglike@dimen/key_heighttosetitdynamicallyfordifferentscreensizes.
Gap:Thehorizontalandverticalgaptellshowmuchspacetoleavebetweenkeys.Evenifyousetitto0pxthereisstillasmallgap.
codes:ThiscanbeaUnicodeorcustomcodevaluethatdetermineswhathappensorwhatisinputwhenthekeyispressed.SeekeyOutputTextifyouwanttoinputalongerUnicodestring.
keyLabel:Thisisthetextthatisdisplayedonthekey.
keyEdgeFlags:Thisindicateswhichedgethekeyshouldbealignedto.
isRepeatable:Ifyouholddownthekeyitwillkeeprepeatingtheinput.
method.xml
Thisfiletellsthesystemtheinputmethodsubtypesthatareavailable.Iamjustincludingaminimalversionhere.
4.AddtheJavacodetohandlekeyinput
CreateanewJavafile.Let'scallitMyInputMethodService.Thisfiletieseverythingtogether.Ithandlesinputreceivedfromthekeyboardandsendsitontowhateverviewisreceivingit(anEditText,forexample).
publicclassMyInputMethodServiceextendsInputMethodServiceimplementsKeyboardView.OnKeyboardActionListener{
@Override
publicViewonCreateInputView(){
//gettheKeyboardViewandaddourKeyboardlayouttoit
KeyboardViewkeyboardView=(KeyboardView)getLayoutInflater().inflate(R.layout.keyboard_view,null);
Keyboardkeyboard=newKeyboard(this,R.xml.number_pad);
keyboardView.setKeyboard(keyboard);
keyboardView.setOnKeyboardActionListener(this);
returnkeyboardView;
}
@Override
publicvoidonKey(intprimaryCode,int[]keyCodes){
InputConnectionic=getCurrentInputConnection();
if(ic==null)return;
switch(primaryCode){
caseKeyboard.KEYCODE_DELETE:
CharSequenceselectedText=ic.getSelectedText(0);
if(TextUtils.isEmpty(selectedText)){
//noselection,sodeletepreviouscharacter
ic.deleteSurroundingText(1,0);
}else{
//deletetheselection
ic.commitText("",1);
}
break;
default:
charcode=(char)primaryCode;
ic.commitText(String.valueOf(code),1);
}
}
@Override
publicvoidonPress(intprimaryCode){}
@Override
publicvoidonRelease(intprimaryCode){}
@Override
publicvoidonText(CharSequencetext){}
@Override
publicvoidswipeLeft(){}
@Override
publicvoidswipeRight(){}
@Override
publicvoidswipeDown(){}
@Override
publicvoidswipeUp(){}
}
Notes:
TheOnKeyboardActionListenerlistensforkeyboardinput.Itisalsorequiresallthoseemptymethodsinthisexample.
TheInputConnectioniswhatisusedtosendinputtoanotherviewlikeanEditText.
5.Updatethemanifest
Iputthislastratherthanfirstbecauseitreferstothefileswealreadyaddedabove.Toregisteryourcustomkeyboardasasystemkeyboard,youneedtoaddaservicesectiontoyourAndroidManifest.xmlfile.Putitintheapplicationsectionafteractivity.
...
That'sit!Youshouldbeabletorunyourappnow.However,youwon'tseemuchuntilyouenableyourkeyboardinthesettings.
6.EnablethekeyboardinSettings
EveryuserwhowantstouseyourkeyboardwillhavetoenableitintheAndroidsettings.Fordetailedinstructionsonhowtodothat,seethefollowinglink:
HowtosetthedefaultkeyboardonyourAndroidphone
Hereisasummary:
GotoAndroidSettings>Languagesandinput>Currentkeyboard>Choosekeyboards.
YoushouldseeyourCustomKeyboardonthelist.Enableit.
GobackandchooseCurrentkeyboardagain.YoushouldseeyourCustomKeyboardonthelist.Chooseit.
NowyoushouldbeabletouseyourkeyboardanywherethatyoucantypeinAndroid.
Furtherstudy
Thekeyboardaboveisusable,buttocreateakeyboardthatotherpeoplewillwanttouseyouwillprobablyhavetoaddmorefunctionality.Studythelinksbelowtolearnhow.
CreatinganInputMethod(Androiddocumentation)
SoftKeyboard(sourcecodefromAndroidforademocustomkeyboard)
BuildingaCustomAndroidKeyboard(tutorial)(sourcecode)
CreateaCustomKeyboardonAndroid(tutsplustutorial)
Howtocreatecustomkeyboardforandroid(YouTubevideo:ItissoundlessbutfollowingalongishowIfirstlearnedhowtodothis.)
GoingOn
Don'tlikehowthestandardKeyboardViewlooksandbehaves?Icertainlydon't.Itlookslikeithasn'tbeenupdatedsinceAndroid2.0.HowaboutallthosecustomkeyboardsinthePlayStore?Theydon'tlookanythingliketheuglykeyboardabove.
Thegoodnewsisthatyoucancompletelycustomizeyourownkeyboard'slookandbehavior.Youwillneedtodothefollowingthings:
CreateyourowncustomkeyboardviewthatsubclassesViewGroup.YoucouldfillitwithButtonsorevenmakeyourowncustomkeyviewsthatsubclassView.Ifyouusepopupviews,thennotethis.
Addacustomeventlistenerinterfaceinyourkeyboard.CallitsmethodsforthingslikeonKeyClicked(Stringtext)oronBackspace().
Youdon'tneedtoaddthekeyboard_view.xml,key_preview.xml,ornumber_pad.xmldescribedinthedirectionsabovesincetheseareallforthestandardKeyboardView.YouwillhandlealltheseUIaspectsinyourcustomview.
InyourMyInputMethodServiceclass,implementthecustomkeyboardlistenerthatyoudefinedinyourkeyboardclass.ThisisinplaceofKeyboardView.OnKeyboardActionListener,whichisnolongerneeded.
InyourMyInputMethodServiceclass'sonCreateInputView()method,createandreturnaninstanceofyourcustomkeyboard.Don'tforgettosetthekeyboard'scustomlistenertothis.
Share
Follow
editedMay24'19at15:32
answeredJul6'17at4:27
SuragchSuragch
397k256256goldbadges12291229silverbadges12661266bronzebadges
0
Addacomment
|
91
Firstofallyouwillneedakeyboard.xmlfilewhichwillbeplacedintheres/xmlfolder(ifthefolderdoesnotexist,createdit).
**Notethatyouwillhavetocreatethebackspacedrawableandplaceitintheres/drawable-ldpifolderwithaverysmallsize(like18x18pixels)
Theninthexmlfilethatyouwantittobeused(whereyourTextViewisin)youshouldaddthefollowingcode:
.....
......
**Notethatthexmlfilethatyouwillplacetheandroid.inputmethodservice.KeyboardViewin,hastobeRelativeLayoutinordertobeabletosetthealignParentBottom="true"(Usuallythekeyboardsarepresentedinthebottomofthescreen)
ThenyouneedtoaddthefollowingcodeintheonCreatefunctionoftheActivitythathandlestheTextViewyouwanttoattachthekeyboardto
//CreatetheKeyboard
mKeyboard=newKeyboard(this,R.xml.keyboard);
//LookuptheKeyboardView
mKeyboardView=(KeyboardView)findViewById(R.id.keyboardview);
//Attachthekeyboardtotheview
mKeyboardView.setKeyboard(mKeyboard);
//Donotshowthepreviewballoons
//mKeyboardView.setPreviewEnabled(false);
//Installthekeyhandler
mKeyboardView.setOnKeyboardActionListener(mOnKeyboardActionListener);
**NotethatmKeyboardandmKeyboardViewareprivateclassvariablesthatyouhavetocreate.
Thenyouneedthefollowingfunctionforopeningthekeyboard(youmustassociateitwiththeTextViewthroughtheonClickxmlproperty)
publicvoidopenKeyboard(Viewv)
{
mKeyboardView.setVisibility(View.VISIBLE);
mKeyboardView.setEnabled(true);
if(v!=null)((InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(v.getWindowToken(),0);
}
AndfinallyyouneedtheOnKeyboardActionListenerthatwillhandleyourevents
privateOnKeyboardActionListenermOnKeyboardActionListener=newOnKeyboardActionListener(){
@OverridepublicvoidonKey(intprimaryCode,int[]keyCodes)
{
//HerechecktheprimaryCodetoseewhichkeyispressed
//basedontheandroid:codesproperty
if(primaryCode==1)
{
Log.i("Key","Youjustpressed1button");
}
}
@OverridepublicvoidonPress(intarg0){
}
@OverridepublicvoidonRelease(intprimaryCode){
}
@OverridepublicvoidonText(CharSequencetext){
}
@OverridepublicvoidswipeDown(){
}
@OverridepublicvoidswipeLeft(){
}
@OverridepublicvoidswipeRight(){
}
@OverridepublicvoidswipeUp(){
}
};
Hopethathelps!!!
Mostofthecodefoundhere
____________________________________________________________-
EDIT:
SinceKeyboardViewisdepreciatedsinceAPIlevel29,youcanfinditscodeinthiswebsiteandcreateaclassinyourcodebeforeimplementingthekeyboardasdescribedabove.
Share
Follow
editedAug20'20at8:17
answeredJul27'14at9:50
PontiosPontios
2,0832121silverbadges2727bronzebadges
5
3
WhatifIdon'twantthekeyboardtobeonthebottomofthescreen?(e.g.Iwanttheusertobeabletodragitaround).IsthatsomethingIcancontrolviamykeyboardapporisithandledbytheandroidsystem?
– user3294126
Mar2'16at21:05
thekeyboardwidthisnotfillingthescreenwhatshouldidotomakeitfillinallscreens
– GeorgeThomas
Aug9'16at7:31
whatistheparentlayoutthattheKeyboardViewisin?Alsohaveyoucheckedthelayout_widthoftheKeyboardView??
– Pontios
Aug9'16at12:37
1
PleasebeawarethatKeyboardViewandKeyboardclassesaredeprecatedbyGooglesinceAPIlevel29.SothissolutionwillnotworkanymoreinfutureifyouhavetotargetanewerAPIlevel.
– maex
Nov14'19at7:03
3
keyboardViewisdeprecatedbygoogle.whatisnewsolution?
– tohidmahmoudvand
Jul25'20at3:04
Addacomment
|
47
In-AppKeyboard
Thisanswertellshowtomakeacustomkeyboardtouseexclusivelywithinyourapp.Ifyouwanttomakeasystemkeyboardthatcanbeusedinanyapp,thenseemyotheranswer.
Theexamplewilllooklikethis.Youcanmodifyitforanykeyboardlayout.
1.StartanewAndroidproject
InamedmyprojectInAppKeyboard.Callyourswhateveryouwant.
2.Addthelayoutfiles
Keyboardlayout
Addalayoutfiletores/layoutfolder.Icalledminekeyboard.Thekeyboardwillbeacustomcompoundviewthatwewillinflatefromthisxmllayoutfile.Youcanusewhateverlayoutyouliketoarrangethekeys,butIamusingaLinearLayout.Notethemergetags.
res/layout/keyboard.xml
Activitylayout
FordemonstrationpurposesouractivityhasasingleEditTextandthekeyboardisatthebottom.IcalledmycustomkeyboardviewMyKeyboard.(Wewilladdthiscodesoonsoignoretheerrorfornow.)Thebenefitofputtingallofourkeyboardcodeintoasingleviewisthatitmakesiteasytoreuseinanotheractivityorapp.
res/layout/activity_main.xml
3.AddtheKeyboardJavafile
AddanewJavafile.IcalledmineMyKeyboard.
ThemostimportantthingtonotehereisthatthereisnohardlinktoanyEditTextorActivity.Thismakesiteasytoplugitintoanyapporactivitythatneedsit.ThiscustomkeyboardviewalsousesanInputConnection,whichmimicsthewayasystemkeyboardcommunicateswithanEditText.Thisishowweavoidthehardlinks.
MyKeyboardisacompoundviewthatinflatestheviewlayoutwedefinedabove.
MyKeyboard.java
publicclassMyKeyboardextendsLinearLayoutimplementsView.OnClickListener{
//constructors
publicMyKeyboard(Contextcontext){
this(context,null,0);
}
publicMyKeyboard(Contextcontext,AttributeSetattrs){
this(context,attrs,0);
}
publicMyKeyboard(Contextcontext,AttributeSetattrs,intdefStyleAttr){
super(context,attrs,defStyleAttr);
init(context,attrs);
}
//keyboardkeys(buttons)
privateButtonmButton1;
privateButtonmButton2;
privateButtonmButton3;
privateButtonmButton4;
privateButtonmButton5;
privateButtonmButton6;
privateButtonmButton7;
privateButtonmButton8;
privateButtonmButton9;
privateButtonmButton0;
privateButtonmButtonDelete;
privateButtonmButtonEnter;
//ThiswillmapthebuttonresourceidtotheStringvaluethatwewantto
//inputwhenthatbuttonisclicked.
SparseArraykeyValues=newSparseArray<>();
//OurcommunicationlinktotheEditText
InputConnectioninputConnection;
privatevoidinit(Contextcontext,AttributeSetattrs){
//initializebuttons
LayoutInflater.from(context).inflate(R.layout.keyboard,this,true);
mButton1=(Button)findViewById(R.id.button_1);
mButton2=(Button)findViewById(R.id.button_2);
mButton3=(Button)findViewById(R.id.button_3);
mButton4=(Button)findViewById(R.id.button_4);
mButton5=(Button)findViewById(R.id.button_5);
mButton6=(Button)findViewById(R.id.button_6);
mButton7=(Button)findViewById(R.id.button_7);
mButton8=(Button)findViewById(R.id.button_8);
mButton9=(Button)findViewById(R.id.button_9);
mButton0=(Button)findViewById(R.id.button_0);
mButtonDelete=(Button)findViewById(R.id.button_delete);
mButtonEnter=(Button)findViewById(R.id.button_enter);
//setbuttonclicklisteners
mButton1.setOnClickListener(this);
mButton2.setOnClickListener(this);
mButton3.setOnClickListener(this);
mButton4.setOnClickListener(this);
mButton5.setOnClickListener(this);
mButton6.setOnClickListener(this);
mButton7.setOnClickListener(this);
mButton8.setOnClickListener(this);
mButton9.setOnClickListener(this);
mButton0.setOnClickListener(this);
mButtonDelete.setOnClickListener(this);
mButtonEnter.setOnClickListener(this);
//mapbuttonsIDstoinputstrings
keyValues.put(R.id.button_1,"1");
keyValues.put(R.id.button_2,"2");
keyValues.put(R.id.button_3,"3");
keyValues.put(R.id.button_4,"4");
keyValues.put(R.id.button_5,"5");
keyValues.put(R.id.button_6,"6");
keyValues.put(R.id.button_7,"7");
keyValues.put(R.id.button_8,"8");
keyValues.put(R.id.button_9,"9");
keyValues.put(R.id.button_0,"0");
keyValues.put(R.id.button_enter,"\n");
}
@Override
publicvoidonClick(Viewv){
//donothingiftheInputConnectionhasnotbeensetyet
if(inputConnection==null)return;
//Deletetextorinputkeyvalue
//AllcommunicationgoesthroughtheInputConnection
if(v.getId()==R.id.button_delete){
CharSequenceselectedText=inputConnection.getSelectedText(0);
if(TextUtils.isEmpty(selectedText)){
//noselection,sodeletepreviouscharacter
inputConnection.deleteSurroundingText(1,0);
}else{
//deletetheselection
inputConnection.commitText("",1);
}
}else{
Stringvalue=keyValues.get(v.getId());
inputConnection.commitText(value,1);
}
}
//Theactivity(orsomeparentorcontroller)mustgiveus
//areferencetothecurrentEditText'sInputConnection
publicvoidsetInputConnection(InputConnectionic){
this.inputConnection=ic;
}
}
4.PointthekeyboardtotheEditText
Forsystemkeyboards,AndroidusesanInputMethodManagertopointthekeyboardtothefocusedEditText.Inthisexample,theactivitywilltakeitsplacebyprovidingthelinkfromtheEditTexttoourcustomkeyboardto.
Sincewearen'tusingthesystemkeyboard,weneedtodisableittokeepitfrompoppingupwhenwetouchtheEditText.Second,weneedtogettheInputConnectionfromtheEditTextandgiveittoourkeyboard.
MainActivity.java
publicclassMainActivityextendsAppCompatActivity{
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditTexteditText=(EditText)findViewById(R.id.editText);
MyKeyboardkeyboard=(MyKeyboard)findViewById(R.id.keyboard);
//preventsystemkeyboardfromappearingwhenEditTextistapped
editText.setRawInputType(InputType.TYPE_CLASS_TEXT);
editText.setTextIsSelectable(true);
//passtheInputConnectionfromtheEditTexttothekeyboard
InputConnectionic=editText.onCreateInputConnection(newEditorInfo());
keyboard.setInputConnection(ic);
}
}
IfyourActivityhasmultipleEditTexts,thenyouwillneedtowritecodetopasstherightEditText'sInputConnectiontothekeyboard.(YoucandothisbyaddinganOnFocusChangeListenerandOnClickListenertotheEditTexts.Seethisarticleforadiscussionofthat.)Youmayalsowanttohideorshowyourkeyboardatappropriatetimes.
Finished
That'sit.Youshouldbeabletoruntheexampleappnowandinputordeletetextasdesired.Yournextstepistomodifyeverythingtofityourownneeds.Forexample,insomeofmykeyboardsI'veusedTextViewsratherthanButtonsbecauseitiseasiertocustomizethem.
Notes
Inthexmllayoutfile,youcouldalsouseaTextViewratheraButtonifyouwanttomakethekeyslookbetter.Thenjustmakethebackgroundbeadrawablethatchangestheappearancestatewhenpressed.
Advancedcustomkeyboards:Formoreflexibilityinkeyboardappearanceandkeyboardswitching,IamnowmakingcustomkeyviewsthatsubclassViewandcustomkeyboardsthatsubclassViewGroup.Thekeyboardlaysoutallthekeysprogrammatically.Thekeysuseaninterfacetocommunicatewiththekeyboard(similartohowfragmentscommunicatewithanactivity).Thisisnotnecessaryifyouonlyneedasinglekeyboardlayoutsincethexmllayoutworksfineforthat.ButifyouwanttoseeanexampleofwhatIhavebeenworkingon,checkoutalltheKey*andKeyboard*classeshere.NotethatIalsouseacontainerviewtherewhosefunctionitistoswapkeyboardsinandout.
Share
Follow
editedFeb7'18at16:28
answeredJul10'17at7:06
SuragchSuragch
397k256256goldbadges12291229silverbadges12661266bronzebadges
15
youranswerisgreat,buthowcanwesettogglingbetweenanoriginalkeyboardandthisnewkeyboard.
– KishanDonga
Mar20'18at6:35
@KishanDonga,Onyourkeyboardyoucanaddakeytoswitchkeyboards.WhentheuserpressesitcallInputMethodManager#showInputMethodPicker().Iftheoriginalkeyboarddoesnothavesuchakey,though,theonlywayuserscanswitchtoyourkeyboardistodoitmanuallyinthesystemsettings.AppleissuperiortoAndroidinthisarea,becauseApplerequiresallkeyboardstohaveakeyboardswitchingkey.
– Suragch
Mar20'18at7:56
@KishanDonga,Ijustrealizedthatthisanswerisaboutanin-appkeyboard,notthesystemkeyboard.Ifyouwanttoswapbetweentwocustomkeyboards,thenyoucanprogrammaticallyswaptheminandoutofacontainerview.Justaddaswapkeyboardskeyonbothkeyboards.Seemy"advancedcustomkeyboards"noteandlinkintheanswerabove.
– Suragch
Mar20'18at8:02
2
@MarekTakac,youwillneedtodisablethesystemkeyboardandaddyourcustomkeyboardineveryactivity.IfanactivityhasmultipleEditTextsthenyouwillneedtoaddanonFocusChangedListenertothemsothatwhentheyreceivefocusyoucanassigntheInputConnectionfromthecurrentEditTexttoyourcustomkeyboard.
– Suragch
Jul15'18at10:58
3
"preventsystemkeyboardfromappearingwhenEditTextistapped"isnotworking,thesystemkeyboardstillpopsup.editText.setShowSoftInputOnFocus(false);andnowworks
– MiguelPynto
Apr9at11:52
|
Show10morecomments
31
UseKeyboardView:
KeyboardViewkbd=newKeyboardView(context);
kbd.setKeyboard(newKeyboard(this,R.xml.custom));
kbd.setOnKeyboardActionListener(newOnKeyboardActionListener(){
....
}
nowyouhavekbdwhichisanormalview.
ThenicethingaboutthisisthatR.xml.customrefersto/res/xml/custom.xml,whichdefinesinxmlthelayoutofthekeyboard.Formoreinformationonthisfile,lookhere:Keyboard,Keyboard.Row,Keyboard.Key.
Share
Follow
answeredAug12'12at16:20
bigstonesbigstones
14.7k66goldbadges6464silverbadges8181bronzebadges
1
4
IamusingKeyboardViewclass,butasofAPI29,itisnowdeprecated.
– Abhijit
May2'20at3:47
Addacomment
|
14
Hereisasampleprojectforasoftkeyboard.
https://developer.android.com/guide/topics/text/creating-input-method.html
Your'sshouldbeinthesamelineswithadifferentlayout.
Edit:
Ifyouneedthekeyboardonlyinyourapplication,itsverysimple!
Createalinearlayoutwithverticalorientation,andcreate3linearlayoutsinsideitwithhorizontalorientation.
Thenplacethebuttonsofeachrowineachofthosehorizontallinearlayouts,andassigntheweightpropertytothebuttons.Useandroid:layout_weight=1forallofthem,sotheygetequallyspaced.
Thiswillsolve.Ifyoudidn'tgetwhatwasexpected,pleasepostthecodehere,andweareheretohelpyou!
Share
Follow
editedMar6'14at22:32
FlorianBrucker
7,92933goldbadges3939silverbadges6464bronzebadges
answeredMar6'12at3:11
nithinreddynithinreddy
6,06644goldbadges3636silverbadges4343bronzebadges
1
TheeditisactuallybadbecausethatwouldmeanthekeyboardisalwaysshownandwillnotbehavelikestockAndroidkeyboard.
– m0skit0
Sep11'18at14:32
Addacomment
|
7
Oneofthebestwell-documentedexampleIfound.
http://www.fampennings.nl/maarten/android/09keyboard/index.htm
KeyboardViewrelatedXMLfileandsourcecodeareprovided.
Share
Follow
answeredFeb9'14at8:30
YoungjaeYoungjae
22.4k1717goldbadges105105silverbadges186186bronzebadges
1
1
KeyboardViewisdeprecatednow
– AlbertoM
Jun22'20at14:34
Addacomment
|
6
IcameacrossthispostrecentlywhenIwastryingtodecidewhatmethodtousetocreatemyowncustomkeyboard.IfoundtheAndroidsystemAPItobeverylimited,soIdecidedtomakemyownin-appkeyboard.UsingSuragch'sanswerasthebasisformyresearch,Iwentontodesignmyownkeyboardcomponent.It'spostedonGitHubwithanMITlicense.Hopefullythiswillsavesomebodyelsealotoftimeandheadache.
Thearchitectureisprettyflexible.Thereisonemainview(CustomKeyboardView)thatyoucaninjectwithwhateverkeyboardlayoutandcontrolleryouwant.
YoujusthavetodeclaretheCustomKeyboardViewinyouactivityxml(youcandoitprogrammaticallyaswell):
ThenregisteryourEditText'swithitandtellitwhattypeofkeyboardtheyshoulduse:
overridefunonCreate(savedInstanceState:Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
valnumberField:EditText=findViewById(R.id.testNumberField)
valnumberDecimalField:EditText=findViewById(R.id.testNumberDecimalField)
valqwertyField:EditText=findViewById(R.id.testQwertyField)
keyboard=findViewById(R.id.customKeyboardView)
keyboard.registerEditText(CustomKeyboardView.KeyboardType.NUMBER,numberField)
keyboard.registerEditText(CustomKeyboardView.KeyboardType.NUMBER_DECIMAL,numberDecimalField)
keyboard.registerEditText(CustomKeyboardView.KeyboardType.QWERTY,qwertyField)
}
TheCustomKeyboardViewhandlestherest!
I'vegottheballrollingwithaNumber,NumberDecimal,andQWERTYkeyboard.Feelfreetodownloaditandcreateyourownlayoutsandcontrollers.Itlookslikethis:
Evenifthisisnotthearchitectureyoudecidetogowith,hopefullyit'llbehelpfultoseethesourcecodeforaworkingin-appkeyboard.
Again,here'sthelinktotheproject:CustomIn-AppKeyboard
EDIT:I'mnolongeranAndroiddeveloper,andInolongermaintainthisGitHubproject.Thereareprobablymoremodernapproachesandarchitecturesatthispoint,butpleasefeelfreetoreferencetheGitHubprojectifyou'dlikeandforkit.
Share
Follow
editedOct17'20at13:26
answeredJul23'18at2:07
DonBrodyDonBrody
1,66722goldbadges1616silverbadges2828bronzebadges
Addacomment
|
2
WellSuragchgavethebestanswersofarbutheskippedcertainminorstuffthatwasimportanttogettingtheappcompiled.
IhopetomakeabetteranswerthanSuragchbyimprovingonhisanswer.Iwilladdallthemissingelementshedidntput.
Icompiledmyapkusingtheandroidapp,APKBuilder1.1.0.Solet'sbegin.
TobuildanAndroidappweneedcouplefilesandfoldersthatareorganizedinacertainformatandcapitalizedaccordingly.
res
layout->xmlfilesdepictinghowappwilllookon
phone.Similartohowhtmlshapeshow
webpagelooksonbrowser.Allowing
yourapptofitonscreensaccordingly.
values->constantdatasuchascolors.xml,
strings.xml,styles.xml.Thesefilesmust
beproperlyspelt.
drawable->pics{jpeg,png,...};Namethem
anything.
mipmap->morepics.usedforappicon?
xml->morexmlfiles.
src
->actslikeJavaScriptinhtml.layout
fileswillinitiatethestartingview
andyourjavafilewilldynamically
controlthetagelementsandtrigger
events.Eventscanalsobeactivated
directlyinthelayout.xmljustlikein
html.
AndroidManifest.xml->
Thisfileregisterswhatyourappisabout.Applicationname,Typeofprogram,permissionsneeded,etc.ThisseemstomakeAndroidrathersafe.ProgramsliterallycannotdowhattheydidntaskforintheManifest.
Nowthereare4typesofAndroidprograms,anactivity,aservice,acontentprovider,andabroadcastreciever.Ourkeyboardwillbeaservice,whichallowsittoruninthebackground.Itwillnotappearinthelistofappstolaunch;butitcanbeuninstalled.
Tocompileyourapp,involvesgradle,andapksigning.YoucanresearchthatoneoruseAPKBuilderforandroid.Itissupereasy.
NowthatweunderstandAndroiddevelopment,letuscreatethefilesandfolders.
CreatethefilesandfoldersasIdiscussedabove.Mydirectorywillookasfollows:
NumPad
AndroidManifest.xml
src
Saragch
num_pad
MyInputMethodService.java
res
drawable
Suragch_NumPad_icon.png
layout
key_preview.xml
keyboard_view.xml
xml
method.xml
number_pad.xml
values
colors.xml
strings.xml
styles.xml
RememberifyouareusinganidesuchasAndroidStudioitmayhaveaprojectfile.
Writefiles.
A:NumPad/res/layout/key_preview.xml
B:NumPad/res/layout/keyboard_view.xml
C:NumPad/res/xml/method.xml
D:Numpad/res/xml/number_pad.xml
Ofcoursethiscanbeeasilyeditedtoyourliking.Youcanevenuseimagesinsteadlfwordsforthelabel.
SuragchdidntdemonstratethefilesinthevaluesfolderandassumedwehadaccesstoAndroidStudio;whichautomaticallycreatesthem.GoodthingIhaveAPKBuilder.
E:NumPad/res/values/colors.xml
#3F51B5
#303F9F
#FF4081
F:NumPad/res/values/strings.xml
SuragchNumPad
G:NumPad/res/values/styles.xml
H:Numpad/AndroidManifest.xml
Thisisthefilethatwasreallyupforcontension.HereIfeltIwouldnevercompilemyprogram.sob.sob.IfyoucheckSuracgh'sansweryouseeheleavesthefirstsetoffieldsempty,andaddstheactivitytaginthisfile.AsIsaidtherearefourtypesofAndroidprograms.Anactivityisaregularappwithalaunchericon.Thisnumpadisnotanactivity!Furtherhedidntimplementanyactivity.
Myfriendsdonotincludetheactivitytag.Yourprogramwillcompile,andwhenyoutrytolaunchitwillcrash!Asforxmlns:androidanduses-sdk;Icanthelpyouthere.Justtrymysettingsiftheywork.
Asyoucanseethereisaservicetag,whichregisteritasaservice.Alsoservice.android:namemustbenameofpublicclassextendingserviceinourjavafile.ItMUSTbecapitalizedaccordingly.Alsopackageisthenameofthepackagewedeclaredinjavafile.
I:NumPad/src/Saragch/num_pad/MyInputMethodService.java
Note:Ithinkjavaisanalternativetosrc.
Thiswasanotherproblemfilebutnotascontentiousasthemanifestfile.AsIknowJavagoodenoughtoknowwhatiswhat,whatisnot.IbarelyknowxmlandhowittiesinwithAndroiddevelopment!
Theproblemherewashedidntimportanything!Imean,hegaveusa"complete"filewhichusesnamesthatcouldntberesolved!InputMethodService,Keyboard,etc.ThatisbadpracticeMr.Suragch.Thanksforhelpingmeoutbuthowdidyouexpectthecodetocompileifthenamescantberesolved?
Followingisthecorrectlyeditedversion.Ijusthappenedtopounceuponcouplehintstodrovemetotherightplacetolearnwhatexactlytoimport.
packageSaragch.num_pad;
importandroid.inputmethodservice.InputMethodService;
importandroid.inputmethodservice.KeyboardView;
importandroid.inputmethodservice.Keyboard;
importandroid.text.TextUtils;
importandroid.view.inputmethod.InputConnection;
importandroid.content.Context;
importandroid.content.Intent;
importandroid.content.pm.PackageManager;
importandroid.os.Build;
importandroid.os.Bundle;
importandroid.view.View;
importandroid.widget.ImageView;
importandroid.widget.TextView;
importandroid.widget.Toast;
publicclassMyInputMethodServiceextendsInputMethodServiceimplementsKeyboardView.OnKeyboardActionListener
{
@Override
publicViewonCreateInputView()
{
//gettheKeyboardViewandaddourKeyboardlayouttoit
KeyboardViewkeyboardView=(KeyboardView)getLayoutInflater().inflate(R.layout.keyboard_view,null);
Keyboardkeyboard=newKeyboard(this,R.xml.number_pad);
keyboardView.setKeyboard(keyboard);
keyboardView.setOnKeyboardActionListener(this);
returnkeyboardView;
}
@Override
publicvoidonKey(intprimaryCode,int[]keyCodes)
{
InputConnectionic=getCurrentInputConnection();
if(ic==null)return;
switch(primaryCode)
{
caseKeyboard.KEYCODE_DELETE:
CharSequenceselectedText=ic.getSelectedText(0);
if(TextUtils.isEmpty(selectedText))
{
//noselection,sodeletepreviouscharacter
ic.deleteSurroundingText(1,0);
}
else
{
//deletetheselection
ic.commitText("",1);
}
ic.deleteSurroundingText(1,0);
break;
default:
charcode=(char)primaryCode;
ic.commitText(String.valueOf(code),1);
}
}
@Override
publicvoidonPress(intprimaryCode){}
@Override
publicvoidonRelease(intprimaryCode){}
@Override
publicvoidonText(CharSequencetext){}
@Override
publicvoidswipeLeft(){}
@Override
publicvoidswipeRight(){}
@Override
publicvoidswipeDown(){}
@Override
publicvoidswipeUp(){}
}
Compileandsignyourproject.
ThisiswhereIamcluelessasanewbyAndroiddeveloper.Iwouldliketolearnitmanually,asIbelieverealprogrammerscancompilemanually.
Ithinkgradleisoneofthetoolsforcompilingandpackagingtoapk.apkseemstobelikeajarfileorararforzipfile.Therearethentwotypesofsigning.debugkeywhichisnotalllowedonplaystoreandprivatekey.
WellletsgiveMr.Saragchahand.Andthankyouforwatchingmyvideo.Like,subscribe.
Share
Follow
editedMay29'19at4:20
marc_s
691k163163goldbadges12821282silverbadges14061406bronzebadges
answeredMay24'19at9:16
user9599745user9599745
Addacomment
|
1
Hadthesameproblem.Iusedtablelayoutatfirstbutthelayoutkeptchangingafterabuttonpress.Foundthispageveryusefulthough.http://mobile.tutsplus.com/tutorials/android/android-user-interface-design-creating-a-numeric-keypad-with-gridlayout/
Share
Follow
answeredAug26'13at9:23
jeydeejeydee
4933bronzebadges
1
3
Notsurewherespaghettiistobefound.Exampleonlyhaslike5linesofcodeimplementingonCreate.
– Glenn
Oct16'13at4:02
Addacomment
|
YourAnswer
ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers.
Draftsaved
Draftdiscarded
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingEmailandPassword
Submit
Postasaguest
Name
Email
Required,butnevershown
PostYourAnswer
Discard
Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy
Nottheansweryou'relookingfor?Browseotherquestionstaggedandroidkeyboardoraskyourownquestion.
TheOverflowBlog
Whoownsthisoutage?BuildingintelligentescalationchainsformodernSRE
Podcast395:Whoisbuildingcloudsfortheindependentdeveloper?
FeaturedonMeta
Nowlive:Afullyresponsiveprofile
Reducingtheweightofourfooter
TwoBornottwoB-Farewell,BoltClockandBhargav!
Linked
1
HowdoIcreateacustomAndroidkeyboardwithnumbers-only?
362
ShowandhideaViewwithaslideup/downanimation
88
Howtodisablekeypadpopupwhenonedittext?
52
HowtocapturesoftkeyboardinputinaView?
28
Java.Correctpatternforimplementinglisteners
20
CreateCustomKeyboardinAndroid
10
Neednumberonlysoftkeyboard?
12
Androidcustomkeyboard-Previewviewconstrainedtoparentlayout
9
PreventkeyboardinwebView
7
CanIusetheAndroidInputMethodManageronacustomin-appkeyboard?
Seemorelinkedquestions
Related
1440
ActivityrestartonrotationAndroid
1147
Flinggesturedetectionongridlayout
1918
HowtogetscreendimensionsaspixelsinAndroid
4135
Howdoyouclose/hidetheAndroidsoftkeyboardprogrammatically?
3058
HowtostopEditTextfromgainingfocusatActivitystartupinAndroid
1453
Howcanyougetthebuild/versionnumberofyourAndroidapplication?
513
Howtoshowsoft-keyboardwhenedittextisfocused
918
HowtosetTextViewtextStylesuchasbold,italic
739
Xcode6:Keyboarddoesnotshowupinsimulator
HotNetworkQuestions
Whatdoesitmeantograntachurchtoapriory?
Whatcould"dippingfromthecompany'scoffers"possiblymean?
IsitlegalintheUStoleaveaguninthehandsofaminorwithoutoversight?
WhydoesHebrews3:1callJesusanapostle?
WhataretheoptionsforaPCwithcoldresistanceanddarkvision?
Sci-fistorywherepeoplearereincarnatedathubsandamanwantstofigureoutwhatishappening
In-TransitWaitingAreainUSAAirports?
WhatshouldIdoideallytorechargeduringaPhD?
Wordforaplanthathasnotbeenperformedbecauseofsomeissues
Whatisthemosthumanewaytokillcrayfishathome?
Projectingshadows,orevenamovie,onthemoon
Meaningof"ruinsomethingforsomeone"
missing$inserted(inatable)
HowshouldIteachlogarithmstohighschoolstudents?
WhyistheSecondAmendmentstructureddifferentlyfromallotheramendments?
Needtolistanyreferencesforcommonknowledge?
Islookingforplaintextstringsonanencrypteddiskagoodtest?
Whythetwooutputsaredifferent?
Whyarecerealgrainssoimportanttoagricultureandcivilization?
HowtojustifysmallHomininsnotbeingconqueredby(anatomicallymodern)Humans?
ConvertRegextoMask
NewtoBikes:MychainfelloffandIputitbackon.HowcanIknowifit'sontherightcog?
Algebraictopologyandhomotopytheorywithsimplicialsetsinsteadoftopologicalspaces
Whatdoes'dosteakandchips'mean?
morehotquestions
Questionfeed
SubscribetoRSS
Questionfeed
TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader.
default
Yourprivacy
Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy.
Acceptallcookies
Customizesettings