Android开发之软键盘用法实例分析
本文实例讲述了Android开发中软键盘用法。分享给大家供大家参考。具体如下:
打开软键盘,有两个方法。一个是showSoftInput,一个是toggleSoftInput。
packagecom.example.dd; importandroid.app.Activity; importandroid.content.Context; importandroid.os.Bundle; importandroid.view.Menu; importandroid.view.View; importandroid.view.View.OnClickListener; importandroid.view.inputmethod.InputMethodManager; importandroid.widget.Button; importandroid.widget.EditText; publicclassMainActivityextendsActivity{ @Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); finalEditTexted2=(EditText)findViewById(R.id.editText2); Buttonb1=(Button)findViewById(R.id.button1); b1.setOnClickListener(newOnClickListener(){ @Override publicvoidonClick(Viewv){ ed2.requestFocus(); show(ed2); } }); Buttonb2=(Button)findViewById(R.id.button2); b2.setOnClickListener(newOnClickListener(){ @Override publicvoidonClick(Viewv){ toggle(); } }); } privatevoidshow(EditTexted2){ InputMethodManagerimm=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(ed2,InputMethodManager.SHOW_IMPLICIT); } privatevoidtoggle(){ InputMethodManagerimm=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(0,0); } @Override publicbooleanonCreateOptionsMenu(Menumenu){ //Inflatethemenu;thisaddsitemstotheactionbarifitispresent. getMenuInflater().inflate(R.menu.main,menu); returntrue; } }
其中show方法在使用之前,必须先让它的第一个参数requestFocus。可以看show方法的注释:
SynonymforshowSoftInput(View,int,ResultReceiver)withoutaresultreceiver:explicitlyrequestthatthecurrentinputmethod'ssoftinputareabeshowntotheuser,ifneeded.
最后的ifneeded两个单词,意思是说,如果调用了这个方法而且确实是有必要显示键盘的时候,才会弹出软键盘。
toggle方法可以随意的打开和关闭软键盘。
希望本文所述对大家的Android程序设计有所帮助。