1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Linkify.addLinksでリンク化したURLの遷移前に確認ダイアログを出したい

Last updated at Posted at 2020-12-19

調べた経緯

teratailでLinkify.addLinksで自動リンク化したものをタップした時にダイアログで
遷移確認のダイアログを出したいとの質問があったので調べた。

解決方法

タップ時、ブラウザに飛ばそうとしてIntentでoverride fun startActivity(intent: Intent?)に入ってくるので
そこでキャッチしてあげれば良い。

override fun startActivity(intent: Intent?) {

        // とりあえず、アラートダイアログから飛んできたときとそれ以外のときを判別
        val alertFlg = intent?.getBooleanExtra("alert", false)

        // アラートダイアログから飛んできてる場合はそのままブラウザを開かせる
        if(alertFlg!!){
            // こいつが呼ばれるとブラウザが開く
            super.startActivity(intent)
            return
        }

        // ダイアログを表示する
        val urlData = intent.data
        AlertDialog.Builder(this)
                .setMessage("アプリを離れます")
                .setPositiveButton("OK") { _, _->
                    val urlStr = Uri.parse(urlData.toString())
                    val myIntent = Intent(Intent.ACTION_VIEW, (Uri.parse(urlStr.toString())))
                    myIntent.putExtra("alert", true)
                    startActivity(myIntent)
                }
                .setNegativeButton("キャンセル", null)
                .show()

    }

実際に動かす際にはもう少し配慮するコードを書く必要がありそうだが
とりあえずキャッチしてダイアログを出すところまでは上記でできる。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?