Android实现点击跳转本地浏览器打开网页的精简方式

编程知识 更新时间:2023-04-22 10:28:34

一般情况下,我们要实现点击跳转本地浏览器打开指定网页,需要在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实现点击跳转本地浏览器打开网页的精简方式

本文发布于:2023-04-17 02:07:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/1fec945566d6f42948c380b22f09142d.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:跳转   打开网页   浏览器   方式   Android

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 82097文章数
  • 6613阅读数
  • 0评论数