【问题标题】:How to set keyboard focus on WebView?如何在 WebView 上设置键盘焦点?
【发布时间】:2011-04-06 15:15:48
【问题描述】:

我有一个简单的 WebView 示例应用,其布局如下:

<?xml version="1.0" encoding="utf-8"?>
<!-- This file is /res/layout/main.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">

  <EditText android:id="@+id/urlToLoad"
    android:hint="Type url to load"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>

  <Button android:id="@+id/webviewgo"
    android:text="Go"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:enabled="false" />

  <com.example.exWebView  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
  />    

</LinearLayout>

它按预期工作,但我对将键盘事件路由到 WebView 感兴趣。目前,即使我选择 WebView(和滚动等)​​,当我键入任何键时,它都会转到 EditText 控件......这不是我想要的。

如何将键盘事件改为转到 WebView?

【问题讨论】:

    标签: android keyboard keyboard-events


    【解决方案1】:

    根据this thread,您所要做的就是在主活动的 OnCreate() 中设置一个带有 requestFocus() 的 OnTouchListener():

        mWebView = (MyWebView) findViewById(R.id.webview);
        mWebView.setOnTouchListener(new View.OnTouchListener() { 
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) { 
                           case MotionEvent.ACTION_DOWN: 
                           case MotionEvent.ACTION_UP: 
                               if (!v.hasFocus()) { 
                                   v.requestFocus(); 
                               } 
                               break; 
                       } 
                       return false; 
                    }
            });
    

    这段代码的基本作用是在任何向下或向上事件到达您的视图时锁定焦点。注意它是如何返回 false 的,以便事件可以进一步传播到其他视图,就好像它没有被处理一样。

    【讨论】:

    • 就我而言,我不得不使用 requestFocusFromTouch() 而不仅仅是 requestFocus()。
    猜你喜欢
    • 1970-01-01
    • 2014-04-22
    • 2011-10-08
    • 1970-01-01
    • 2012-05-14
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 2016-02-27
    相关资源
    最近更新 更多