Android Tutorials

Google+

Friday, 11 October 2013

Android Button Examples

1. Add Button
Open “res/layout/main.xml” file, 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:orientation="vertical" >
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button - Go to google.com" /> 
</LinearLayout>
2. Code
Attach a click listener to the button.
When user click on it, open mobile browser and display URL : http://www.google.com.
File : MyAndroidAppActivity.java

package com.bishnu.android;
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 MyAndroidAppActivity extends Activity {
 Button button;
 @Override
 public 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() {
    @Override
   public void onClick(View arg0) {
     Intent browserIntent =
                            new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
       startActivity(browserIntent);
   }
  });
 }
}

8 comments:

  1. Thanks bro, ur really humble and smart!

    ReplyDelete
  2. i got a question. When the method protected void onSaveInstanceState(Bundle outState) is executed?

    ReplyDelete
  3. thakn you soo much, i was getting so stuck but starting to understand :)

    ReplyDelete
  4. Yes unless you want a app to look like blank page you are going to need to learn XML.

    ReplyDelete
  5. I love this! Great job! I think kids explain things more clearly than adults sometimes!!!!! You should do Java tutorial.

    ReplyDelete
  6. well done, thanks

    ReplyDelete
  7. refer this link
    http://ioscodeios.blogspot.in/

    ReplyDelete