Search code examples
javaandroidwebviewimageview

How can I rewrite the code to open link on Chrome custom tab?


So I have this code in my mainActivity that I use to open the link, but it opens in chrome app and I want it to open in custom-chrome-tabs webView option.

ImageView playtowin;

playtowin = findViewById(R.id.ptw);

    playtowin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            gotoUrl("https://www.xbox.com/pt-BR/play");
        }
    });

      private void gotoUrl(String s) {
        Uri uri = Uri.parse(s);
        startActivity(new Intent(Intent.ACTION_VIEW,uri));
      }

Solution

  • According to the guide here custom-tabs

    first add the dependencies to your app/build.gradle file

    dependencies {
       ...
        implementation "androidx.browser:browser:1.4.0"
    }
    

    your solution should look something like this.

    import android.support.customtabs.CustomTabsIntent;
    
    ImageView playtowin;
    
    playtowin = findViewById(R.id.ptw);
    
    playtowin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openCustomTab("https://www.xbox.com/pt-BR/play");
        }
    });
    
    private void openCustomTab(String url) {
        CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
        CustomTabsIntent customTabsIntent = builder.build();
        customTabsIntent.launchUrl(this, Uri.parse(url));
    }