Android開發之軟鍵盤用法執行個體分析_Android

來源:互聯網
上載者:User

本文執行個體講述了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程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.