How to open a website when a Button is clicked in Android application?

前端 未结 10 2082
囚心锁ツ
囚心锁ツ 2020-12-01 00:23

I am designing an app, with several button for users to click on. Once button is clicked, user is directed to appropriate website. How do I accomplish this?

10条回答
  •  甜味超标
    2020-12-01 01:00

    Add this to your button's click listener:

      Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
        try {
            intent.setData(Uri.parse(url));
            startActivity(intent);
        } catch (ActivityNotFoundException exception) {
            Toast.makeText(getContext(), "Error text", Toast.LENGTH_SHORT).show();
        }
    

    If you have a website url as a variable instead of hardcoded string then don't forget to handle an ActivityNotFoundException and show error. Or you may receive invalid url and app will simply crash. (Pass random string instead of url variable and see for youself )

提交回复
热议问题