[TUT] Button to open web browser

Someone requested this so here goes:

If you want to send someone to a website when they press a button in your activity:

MainActivity class:



package com.blundell.twitterlink;
 
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
 
public class Main extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); //Set the screen's view to your xml file
       
       
        Button twitterButton = (Button) findViewById(R.id.twitterButton); // Retrieve the button from the XML file
        twitterButton.setOnClickListener(new View.OnClickListener() {  //Add a listener for when the button is pressed
                        @Override
                        public void onClick(View v) {
                                sendToTwitter();                       
                        }
                });
    }
 
        protected void sendToTwitter() {
                String url = "https://twitter.com/blundell_apps"; // You could have this at the top of the class as a constant, or pass it in as a method variable, if you wish to send to multiple websites
                Intent i = new Intent(Intent.ACTION_VIEW); // Create a new intent - stating you want to 'view something'
                i.setData(Uri.parse(url));  // Add the url data (allowing android to realise you want to open the browser)
                startActivity(i); // Go go go!
        }
}




And your XML layout:
Main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   >
    <Button
        android:id="@+id/twitterButton"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Send me to Twitter"
            />
</LinearLayout>



As always, enjoy!



2 thoughts on “[TUT] Button to open web browser

  1. Hi Blundell,

    Firstly thanks for your awesome tutorials. I’m just dipping my toes in developing and have found it really useful.
    Could you direct me in how I could create a custom “splash”? screen for the ‘button to opena web browser?
    I’ve basically got myself in a situation where I’ll need to produce a load of these launchers and would rather know/learn how to do it with expert guidance than pay someone a monthly charge to create and manage such apps. That said, I’ll happily give you a tutorial fee if you can help me 🙂
    Many thanks,
    Fraser

Comments are closed.