Simply Clickable Button to URL


  1. skylab8

    skylab8 New Member

    I'm new to android. I have an app. I just want to add to it a button which when clicked opens a browser to "google.com" website. This is the button code:

    <Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:text="Website" />

    I don't know what to put on the activity code. Any help would be appreciated.

    Advertisement
  2. jonbonazza

    jonbonazza Well-Known Member

    Moved to App Development.

    You need to register an OnClickListener and override the onClick() method to load the web page. To do this, you could either use a WebView or send an Intent to open the user's preferred browser.
  3. cr5315

    cr5315 Well-Known Member Developer

    Take the code for your button and add
    Code (Text):
    1. android:onClick="openWebsite"
    to make it look like
    Code (Text):
    1. <Button
    2. android:id="@+id/button1"
    3. android:layout_width="wrap_content"
    4. android:layout_height="wrap_content"
    5. android:layout_alignParentLeft="true"
    6. android:layout_alignParentTop="true"
    7. android:text="Website"
    8. android:onClick="openWebsite" />
    Then in your activity...

    Code (Text):
    1. public void openWebsite(View view) {
    2.     String url = "http://www.example.com";
    3.     Intent i = new Intent(Intent.ACTION_VIEW);
    4.     i.setData(Uri.parse(url));
    5.     startActivity(i);
    6. }
    The android:eek:nClick calls openWebsite() which will then pass String url to Android which will open it in the default browser.
  4. skylab8

    skylab8 New Member

    Thanks a lot for the code. When I pasted your code to the activity I got these errors with "Intent" highlighted in red.
    Intent cannot be resolved to a variable.
    Intent cannot be resolved to a type
    Intent cannot be resolved to a type

    Google suggested to "import "intent" (andoird.conent) as a quick fix.
    When I choose the quick fix Android suggested and run the app. The button was visible, and clickable, but when I click on it the app freezes.
  5. jonbonazza

    jonbonazza Well-Known Member

    When you say freezes, does it show an exception eventually?
  6. skylab8

    skylab8 New Member

    Yes right after I click on the link I get an exception. Thanks!

Share This Page