【问题标题】:Why Does Getting WebView by ID crash at runtime?为什么通过 ID 获取 WebView 在运行时会崩溃?
【发布时间】:2014-05-24 15:23:21
【问题描述】:

我在尝试在活动中显示 web 视图时看到应用程序失败。如果我在 onCreate() 中实例化 webview,而不是获取 R.id.webview,它确实有效。为什么会这样?

这是显示网络视图的活动:

public class DisplayMessageActivity extends ActionBarActivity {

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

        setContentView(R.id.webview);

        WebView myWebView = (WebView) findViewById(R.id.webview);
        myWebView.loadUrl("http://www.example.com");        
    }

布局xml文件:

<WebView  
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
/>

【问题讨论】:

  • 里面没有布局。将setContentView() 参数更改为布局文件
  • setContentView(R.id.webview);?也许布局包含webview?

标签: android webview android-activity


【解决方案1】:

将 cmets 变成答案:

setContentView(R.id.webview);

您不会将视图 ID 传递给此方法,而是传递一个布局文件。然后,您可以使用 findViewById(R.id.webview)
访问包含在该布局中的视图 因此,请改为提供布局 xml 文件。

setContentView(R.layout.my_webview_layout);

或者任何你的布局。

如果它正在记录错误和异常,将来您应该将您的 logcat 日志附加到您的问题中。它识别问题的类型以及它在代码中发生/触发的位置。这样做时还要指出它引用了您发布的代码中的哪一行。

【讨论】:

    猜你喜欢
    • 2016-11-02
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    • 2011-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    相关资源
    最近更新 更多