如何在延迟时间后激活(打开键盘)EditText?

时间:2014-03-06 18:06:56

标签: java android keyboard android-edittext

我有一个EditText和一个CountDownTimer。通常,如果你使用EditText启动一个Activity,EditText会激活并显示键盘。但我希望Activity启动,计时器关闭,然后键盘自动显示。 我怎么能这样做?

new CountDownTimer(5000, 1000) {

         public void onTick(long millisUntilFinished) {
          //Do Something
         }

         public void onFinish() {
             //Keyboard pop up
         }
        }.start();

1 个答案:

答案 0 :(得分:8)

我建议使用Handler postDelayed(...)方法,并在指定的延迟时间后打开键盘:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    final EditText et= (EditText) findViewById(R.id.editText1);
    Handler h = new Handler();

    h.postDelayed(new Runnable() {
        @Override
        public void run() {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
        }

    }, 5000); // delay in milliseconds
}

这将在您所需的延迟时间后打开键盘。

这是我的 .xml文件 :(请注意<requestFocos />标记)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="30dp"
        android:ems="10" >
        <requestFocus />
    </EditText>

</RelativeLayout>
相关问题