Saturday, May 21, 2016

Simplest way to open browser using CustomTabsIntent.Builder


This post show the simplest way to open browser using CustomTabsIntent.Builder.


To use CustomTabsIntent.Builder, edit app/build.gradle to add dependencies of compile 'com.android.support:customtabs:23.0.0'.


MainActivity.java
package com.blogspot.android_er.androidcustomtabsintent;

import android.net.Uri;
import android.os.Bundle;
import android.support.customtabs.CustomTabsIntent;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

Button btnLaunch;
Uri uriMyBlog = Uri.parse("http://android-er.blogspot.com");

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLaunch = (Button)findViewById(R.id.launch);
btnLaunch.setOnClickListener(btnLaunchOnClickListener);
}

View.OnClickListener btnLaunchOnClickListener = new View.OnClickListener(){

@Override
public void onClick(View v) {
new CustomTabsIntent.Builder()
.build()
.launchUrl(MainActivity.this, uriMyBlog);

}
};
}


activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:orientation="vertical"
tools:context="com.blogspot.android_er.androidcustomtabsintent.MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://android-er.blogspot.com/"
android:textStyle="bold" />

<Button
android:id="@+id/launch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Launch"/>
</LinearLayout>


No comments:

Post a Comment