初学Android开发,这段代码在模拟器上会闪退,不知是哪里有问题,求大神解答
package com.kongcheng.light;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
// Info
import android.widget.Toast;
// WebView
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebSettings;
import android.webkit.WebViewClient;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
final WebView webView = findViewById(R.id.WebView);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化WebView
this.initWebView(this.webView);
//初始化UI
this.initUI();
this.webView.loadUrl("https://www.baidu.com/");
}
private void initWebView(WebView webView) {
//覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为,使网页用WebView打开
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
//返回值是true的时候控制去WebView打开,为false调用系统浏览器或第三方浏览器
view.loadUrl(url);
return true;
}
});
//设置
WebSettings settings = webView.getSettings();
//启用支持javascript
//settings.setJavaScriptEnabled(true);
}
private void initUI(){
//返回
Button btn_goBack = this.findViewById(R.id.btnGoBack);
btn_goBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MainActivity.this.webView.goBack();
}
});
//前进
Button btn_goForward = this.findViewById(R.id.btnGoForward);
btn_goForward.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MainActivity.this.webView.goForward();
}
});
}
}
在setContentView(R.layout.activity_main);
前是没有findViewById这个函数的,会报空指针
21-27行应改为:
public class MainActivity extends AppCompatActivity {
WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.webView = findViewById(R.id.WebView);