萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> 安卓開發 >> Android開發之軟鍵盤用法實例分析

Android開發之軟鍵盤用法實例分析

   本文實例講述了Android開發中軟鍵盤用法。分享給大家供大家參考。具體如下:

  打開軟鍵盤,有兩個方法。一個是showSoftInput,一個是toggleSoftInput。

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 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程序設計有所幫助。

copyright © 萬盛學電腦網 all rights reserved