使用Kotlin写一个简单的WebView例子

  • 阅读此文需要对Kotlin基本语法有所了解。
  • 本文只是一个Kotlin简单开发Android Demo入手的文章,不对Kotlin语法特点进行探讨。

此Demo用到Kotlin基本知识点回顾:

一.定义变量:

var:修饰可变变量,如:var a : Int = 0 or var textView : TextView ?= null
val:修饰常量,如:val b = 1 【此后b不能再被重新赋值】

二.伴生对象的使用:

语法特点:

companion object {
    ...
    //此方法可用来定义java中 静态常量等【此Demo用到】 
   //val WEB_URL="http://www.baidu.com" 
   // 类似于在java类中直接定义的常量 static final String WEB_URL="http://www.baidu.com"
  }
三.扩展函数【不扩展说明】
四.语法特点:
var textView : TextView ?= null 
textView=findViewById(R.id.u_text_id)  as TextView
textView?.text?:"null"
  • 上述代码第三行代码类似于 Java 中

textView==null?“null”:textView.getText().toString().isEmpty()?"null" :textView.getText().toString();

开始写Android小Demo

1.用AS创建我们的项目取名为WebViewByKotlin:
  • 修改app目录下的buid.gradle,给项目添加依赖:
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
dependencies {
 .  .  .
 compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
}
  • 修改整个项目的buid.gradle,加入如下依赖包:
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
dependencies {
 classpath 'com.android.tools.build:gradle:2.3.3'
 classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
 // NOTE: Do not place your application dependencies here; they belong
 // in the individual module build.gradle files
}
2.开始写activity_main.xml 代码如下:

3.写MainActivity.kt代码:
class MainActivity : AppCompatActivity() {
    //定义变量
    private var mWebView: WebView? = null
    private var mExitTime = 0L 
    
    companion object {
         // 定义WebView首页地址[伴生对象]
         //定义static final
         val WEB_URL = "http://www.baidu.com"
         val TAG=MainActivity::class.simpleName  //定义Log的TAG
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState)
         setContentView(R.layout.activity_main)
         supportActionBar!!.hide()  //隐藏ActionBar
         initAndSetupView()
    }
    
     // 初始化对象
     fun initAndSetupView() {
         val webViewContainer = findViewById(R.id.web_view_container) as FrameLayout
         val params = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)
         mWebView = WebView(applicationContext)
         webViewContainer.addView(mWebView, params)
         var webSettings = mWebView!!.settings
         webSettings.javaScriptEnabled = true
         webSettings.javaScriptCanOpenWindowsAutomatically = true
         webSettings.allowFileAccess = true// 设置允许访问文件数据
         webSettings.setSupportZoom(true)//支持缩放
         webSettings.javaScriptCanOpenWindowsAutomatically = true
         webSettings.cacheMode = WebSettings.LOAD_NO_CACHE
         webSettings.domStorageEnabled = true
         webSettings.databaseEnabled = true
         mWebView!!.setOnKeyListener(OnKeyEvent)
         mWebView!!.setWebViewClient(webClient)
         mWebView!!.loadUrl(WEB_URL)
    }
    
    private val webClient = object : WebViewClient() {
         override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
             Log.d(TAG, url) 
             return false
         }
       }
    
    private val OnKeyEvent = View.OnKeyListener { v, keyCode, event ->
         val action = event.action
         val webView = v as WebView
         if (KeyEvent.ACTION_DOWN == action && KeyEvent.KEYCODE_BACK == keyCode) {
             if (webView?.canGoBack()) {
                 webView.goBack()
                 return@OnKeyListener true
             }
            }
         false
    }
    
    override fun onBackPressed() {
         if ((System.currentTimeMillis() - mExitTime) > 2000) {
             showToast("连按两下退出应用")
             //showToast("连按两下退出应用",Toast.LENGTH_SHORT) //此种方法调用也可以 有点可变参数的意思在里面
             mExitTime = System.currentTimeMillis()
        } else {
            super.onBackPressed()
         }
    }
    
    override fun onResume() {
         super.onResume()
         mWebView?.onResume()
    }
    
    override fun onPause() {
         super.onPause()
         mWebView?.onPause()
    }
    
    override fun onDestroy() {
         super.onDestroy()
         mWebView?.clearCache(true)
         (mWebView?.parent as FrameLayout).removeView(mWebView)
         mWebView?.stopLoading()
         mWebView?.setWebViewClient(null)
         mWebView?.setWebChromeClient(null)
         mWebView?.removeAllViews()
         mWebView?.destroy()
         mWebView = null
    }
    
    //扩展函数
    fun MainActivity.showToast(message: String, length: Int = Toast.LENGTH_SHORT) {
        Toast.makeText(this, message, length).show()
    }
}

*mWebView?.xxx 操作 代码验证后 得出类似于java中

if (mWebView != null) {
  mWebView.xxx;
}
以上内容如有不对之处,欢迎读者指正,谢谢!!!

你可能感兴趣的:(使用Kotlin写一个简单的WebView例子)