我16岁,试图学习Kotlin,我很新。我想创建一个搜索栏,它既搜索Google,又可以打开您键入的任何URL。我试图使用if else
语句,例如:
if
”的前三个字母是“ www。”。然后使用等于“ https://”,else
使用字符串start_url,该字符串等于“ google.com/search?q=“;。 我只是不知道该怎么做,我曾尝试过通过互联网寻求帮助,我只是做不到。
URLUtil.isValidUrl(url)将不起作用,因为它仍然仅加载Google搜索
我愿意接受任何评论,以尝试帮助我进一步学习和改进我的代码,即使它与我的问题无关。指出任何错误或需要改进的代码,我知道这不是完美的,谢谢!
package com.example.corie.quicklinks.mainpages
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.asynclayoutinflater.R.id.text
import android.webkit.WebChromeClient
import android.webkit.WebViewClient
import com.example.corie.quicklinks.R
import com.example.corie.quicklinks.R.string.start_url
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//------------------WEBVIEW-----------------//
webViewOne.webChromeClient = WebChromeClient()
webViewOne.isVerticalScrollBarEnabled = false
webViewOne.run{
webViewOne.loadUrl("https://" + getString(start_url))
}
goBtn.setOnClickListener{
webViewOne.loadUrl("https://www.google.com/search?q=" + editText.text.toString())
}
backBtn.setOnClickListener {
if (webViewOne.canGoBack())
webViewOne.goBack()
}
nextBtn.setOnClickListener {
if (webViewOne.canGoForward())
webViewOne.goForward()
}
//------------------WEBVIEW-----------------//
}
}
带有内置正则表达式模式的简单方法:
import android.util.Patterns
val isAddress = Patterns.WEB_URL.matcher(address).matches()
if (isAddress) {
[email protected]
.loadUrl(address)
} else {
[email protected](
"https://www.google.com/search?q=$address"
)
}