Search code examples
javaandroidxmltextview

Creating a clickable link in TextView without anchor tag in android


I want the user to enter a link in an EditView and when the user clicks enter button, the entered text should show up as a clickable link TextView. Is there any possible way to achieve this?


Solution

  • You can use Intent to open that url when the TextView is clicked. It will open your link in browser but the url text will not become hyperlink.

    Here is the code:

        TextView tv = findViewById(R.id.text_view);
        tv.setOnClickListener(view -> {
            String url = tv.getText().toString();
            if (!url.isEmpty()){
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(url));
                try {
                    startActivity(i);
                } catch (ActivityNotFoundException e) {
                    Toast.makeText(this, "Download a browser to view", Toast.LENGTH_SHORT).show();
                }
            }
        });
    

    For api level 30+ add queries in your manifest file to launch browser from your app outside <application> tag

    <queries>
        <intent>
            <action android:name="android.intent.action.VIEW" />
            <data android:scheme="http" />
    </queries>