Button plays a very important role in app development. It would be next to impossible to design an app without using a button. Let's have a look at this important component in this post.
In this tutorial, we shall learn how to display a normal button, add a click listener and open a URL in your Android’s internet browser, when a user clicks on the button.
File : res/layout/main.xml
File : MainActivity.java
In this tutorial, we shall learn how to display a normal button, add a click listener and open a URL in your Android’s internet browser, when a user clicks on the button.
1. Add Button
Let us first add the button in the layout file. Open “res/layout/main.xml” file, and add a button.File : res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:gravity="center"android:orientation="vertical" ><Buttonandroid:id="@+id/button1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Go to mobilitytutorials blog" /></LinearLayout>
2. Code
We shall attach a click listener to the button so that when a user clicks on it, mobile browser is opened and the URL: "http://mobilitytutorials.blogspot.in" is displayed.File : MainActivity.java
package com.endeavour.buttontutorial;import android.app.Activity;import android.content.Intent;import android.net.Uri;import android.os.Bundle;import android.widget.Button;import android.view.View;import android.view.View.OnClickListener;public class MainActivity extends Activity {Button button;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);addListenerOnButton();}public void addListenerOnButton(){button = (Button)findViewById(R.id.button1);button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://mobilitytutorials.blogspot.in/p/index.html"));startActivity(browserIntent);}});}}
3. Output
The following output shall be displayed:
1. Button on the home screen
No comments:
Post a Comment