• 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
Oct 24, 2012
3
0
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.
 
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:eek:nClick calls openWebsite() which will then pass String url to Android which will open it in the default browser.
 
Upvote 0
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.
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones