Friday 13 December 2013

Android : Open URL on button click.

In this tutorial we will learn how to open URL on button click.

1. Create New Android Application Project. Name it as UrlButton.








2. Open Your activity_main.xml file.
3. Replace your activity_main.xml code with below code.


<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="35dp"
        android:text="Open URL " />

</RelativeLayout>

 Your activity_main.xml will look like below

5 . Open your Mainactivity.java file.

6 . Replace Your Mainactivity.java code with below code.
 

package arshad.urlbutton;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


public class MainActivity extends Activity {
 Button button1;
       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              button1=(Button)findViewById(R.id.button1);
             
              button1.setOnClickListener(new OnClickListener() {

                     @Override
                     public void onClick(View arg0) {
                           Intent intent =new Intent(Intent.ACTION_VIEW,Uri.parse("http://technologyarshadshaikh.blogspot.in"));
                           startActivity(intent); 
                          
                     }
       });
       }

       @Override
       public boolean onCreateOptionsMenu(Menu menu) {
              // Inflate the menu; this adds items to the action bar if it is present.
              getMenuInflater().inflate(R.menu.main, menu);
              return true;
       }

}

 7. Now Build And Run Your Application.

You will be redirected to the url on button click
All The Best.