分享好友 移动开发首页 频道列表

Android开发之软键盘用法实例分析

Android开发  2015-06-24 22:420

本文实例讲述了Android开发中软键盘用法。分享给大家供大家参考。具体如下:

打开软键盘,有两个方法。一个是showSoftInput,一个是toggleSoftInput。

package com.example.dd; 
import android.app.Activity; 
import android.content.Context; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.inputmethod.InputMethodManager; 
import android.widget.Button; 
import android.widget.EditText; 
public class MainActivity extends Activity { 
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    final EditText ed2 = (EditText) findViewById(R.id.editText2);
    Button b1 = (Button) findViewById(R.id.button1); 
    b1.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
        ed2.requestFocus(); 
        show(ed2); 
      } 
    });
    Button b2 = (Button) findViewById(R.id.button2);
    b2.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        toggle();
      }
    });
  }
  private void show(EditText ed2) {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(ed2, InputMethodManager.SHOW_IMPLICIT);
  }
  private void toggle() {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(0, 0);
  }
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }
}

其中show方法在使用之前,必须先让它的第一个参数requestFocus。可以看show方法的注释:

Synonym for showSoftInput(View, int, ResultReceiver) without a result receiver: explicitly request that the current input method's soft input area be shown to the user, if needed.

最后的 if needed两个单词,意思是说,如果调用了这个方法而且确实是有必要显示键盘的时候,才会弹出软键盘。

toggle方法可以随意的打开和关闭软键盘。

希望本文所述对大家的Android程序设计有所帮助。

查看更多关于【Android开发】的文章

展开全文
相关推荐
反对 0
举报 0
评论 0
图文资讯
热门推荐
优选好物
更多热点专题
更多推荐文章
SDK热更之如何在SDK代码中自动插桩及如何生成补丁包
写在前面本文是SDKHotfix相关的SDK热更系列文章中的一篇,以下为项目及系列文章相关链接:SDKHotfix整体介绍:http://blog.bihe0832.com/sdk_hotfix_project.htmlSDKHotfix对应github地址:https://github.com/bihe0832/SDKHoxFix这篇文章主要介绍一下SDK热更

0评论2017-02-05358

Supporting Multiple Screens
术语和概念Screen size 屏幕尺寸又称「屏幕大小」,是屏幕对角线的物理尺寸。单位英寸 inch,比如 Samsung Note4 是 5.7 英寸。Resolution 屏幕分辨率屏幕纵横方向上物理像素的总数,比如 Samsung Note4 是 2560x1440,表示纵向有 2560 个像素,横向有 1440

0评论2017-02-05363

AssetBundle里的Shader问题
关于Resources和AssetBundle优劣之前已经提过很多次了(参考官方教程The Resources folder),正好最近@张迪在做框架AssetBundle部分的优化,特此整理一下两个特常见的坑及对应解决办法。之前在关于Unity中的资源管理,你可能遇到这些问题里有有人提到过这个问

0评论2017-02-05610

ASimpleCache
ASimpleCache 是一个为android制定的 轻量级的 开源缓存框架。轻量到只有一个java文件(由十几个类精简而来)。1、它可以缓存什么东西?普通的字符串、JsonObject、JsonArray、Bitmap、Drawable、序列化的java对象,和 byte数据。2、它有什么特色?特色主要是

0评论2017-02-05376

更多推荐