• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Simply Clickable Button to URL

skylab8

Lurker
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.
 
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.
 
Take the code for your button and add
Code:
android:onClick="openWebsite"
to make it look like
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"
android:onClick="openWebsite" />

Then in your activity...

Code:
public void openWebsite(View view) {
    String url = "http://www.example.com";
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setData(Uri.parse(url));
    startActivity(i);
}

The android:onClick calls openWebsite() which will then pass String url to Android which will open it in the default browser.
 
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.
 
Back
Top Bottom