Android Button Example- How to add button in android application.

Button is a very common component in user interface.You can write text or put any icon on button so user can understand what action occurs when they press or touches it.
In Android programming to display a normal button “android.widget.Button” class is used.
I will show you, How to add button in android application and the use of click listener. When user touches the button then the URL which is written in “onClick listener” opens in a default browser.
Now, the steps for creating this application are :

  1. Design your UI in .xml file.
  2. Create a java file.
  3. Add onClick listener in java file.

Your activity_main.xml file :

<?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:orientation="vertical" >

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button - Go to www.vivekbarot.com" />

</LinearLayout>

Once you Design your UI in “activity_main.xml” file, Write your code in “MainActivity.java” file.

Your MainActivity.java file:

package com.example.button;

import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends ActionBarActivity {

Button button;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}

private void addListenerOnButton() {
// TODO Auto-generated method stub

button = (Button) findViewById(R.id.button1);

button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {

Intent browserIntent =
new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.vivekbarot.com"));
startActivity(browserIntent);

}

});

}

@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;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Now run it as Android application.

 Here is the first view of applicatin :


Now, This is second view of application when you touches the button.


Leave a Reply

Your email address will not be published. Required fields are marked *