一般情况下,我们要实现点击跳转本地浏览器打开指定网页,需要在activity文件中定位到相关控件,再setOnClickListener。如果只有一处需要跳转,这样写也可以,但如果多处存在这样的操作,我们可以使用一种精简的方法:创建一个网页跳转的接口,在layout文件中直接绑定。
本文阅读前提:了解Android中的databinding。
例如,我们创建了一个interface:
interface OpenWebLinkInterface {
fun openWebLink(context: Context, link: String) {
val intent = Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse(link)
}
context.startActivity(intent)
}
}
在layout中放置一个button,通过databinding实现点击跳转打开浏览器网页:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android/apk/res/android"
xmlns:app="http://schemas.android/apk/res-auto">
<data>
<!-- 网页链接在model中 -->
<variable
name="model"
type="com.example.android.app.model.data.CellModel" />
<!-- 调用上面写的接口 -->
<variable
name="handler"
type="com.example.android.app.interfaces.OpenWebLinkInterface" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:orientation="vertical">
<!-- 给button绑定onclick事件,使用匿名函数 -->
<Button
android:id="@+id/jump_to_broswer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="@{(v) -> handler.openWebLink(context, model.Url)}"
android:text="Jump"/>
</LinearLayout>
</Layout>
最后只需要在Activity的onCreate函数下添加binding:
val binding = DataBindingUtil.setContentView<ActivityMainBinding>(
this,
R.layout.activity_main
)
binding.handler = this
大功告成!
更多推荐
Android实现点击跳转本地浏览器打开网页的精简方式
发布评论