Kotlin - Define a variable globally for WebView

I am trying to define a variable globally that belongs to the WebView class. In Android Java, this is easy to do by writing it.

Java for a global variable

< ClassName > < variableName > 

But in Kotlin, I run into a problem with his announcement.


 class MainActivity : AppCompatActivity() { var mywebview : WebView //<- This shows Property must be initialized or be abstract override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } override fun onStart() { super.onStart() mywebview = findViewById(R.id.webViewGyrix) as WebView mywebview.setWebViewClient(object : WebViewClient() { override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean { view?.loadUrl(url); return true } } ) mywebview.loadUrl("http://www.example.com/") } 
+5
source share
4 answers

This indicates that the property must be initialized or abstract.

Then initialize it, that is, to null . This is not the final value, and you can change it later:

 var mywebview : WebView? = null; 
+5
source

You can use late initialization - you do not need to change the value of WebView

 lateinit var webView: WebView 
+15
source

for a global variable, this means that it should not be overridden by accident, so you should instead use lazyload with kotlin lazy, which create the variable on the first call, other calls will just refer to the lazy loaded variable

 private val webview:WebView by lazy{ findViewById<WebView>(R.id.webview) } 

This should happen before the onCreate method

0
source

Below code worked for me:

 val mywebviewURL = "https://www.google.com" override fun onStart() { super.onStart() events_webview.setWebViewClient(object : WebViewClient() { override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean { view?.loadUrl(url); return true } }) events_webview.loadUrl(mywebviewURL) } 

Add internet permission to AndroidManifest.xml

 <uses-permission android:name="android.permission.INTERNET"/> 
0
source

Source: https://habr.com/ru/post/1266973/


All Articles