Android button example

 How to do it :

Create New android project “androidButton” (If you don’t know how to create new project then follow this lesson click here) then :

1. Add the button : You’re going to add a new button to your app’s screen

2 Hide the Msg text : After adding the button, you’re going to hide the msg text.

3. Make the button show the Msg : Next, you’re going to wire up the button to show the Msg.

Add the button :

You need work with the activity_main.xml or  fragment_main.xml (if you are using updated version of sdk like 4.4 then you need add button on this layout xml file) layout file defines the entire layout for your app’s screen. This is where you’re going to add the new button to your app. Open activity_main.xml  by double clicking on it.

Open main.xml now. You can find it under /res/ layout/acivity_main.xml 

or /res/ layout/fragment_main.xml   (if SDK version 4.4 or later )

now you edited the XML layout in the raw XML source. Now you’re going to add a component using the graphical editor. Click on the ‘Graphical Layout’ tab to view the layout in the graphical editor if it isn’t already showing. Notice all  of the Views in the list on the left side of the screen.

android button exampleNote : This example (Project) is developed in Eclipse Version Kepler, tested on Android 4.4.2 (KitKat Version) and SDK build-tools 22.6.3

You can add views to your screen by dragging them from the list onto your screen.

android button example

 

Now click back to the activity_main.xml or  fragment_main.xml the XML. You’ll the first View defined in the file is the Button you just added!

you need msg show after click button so need hide the text :

Make a button show msg

Now define button in main activity

Open MainActivity.xml now. You can find it under /src/com.androidinterview.button/MainAcitvity.xml

The button is expecting to call a method in this class. Since the MainActivity is setting the activity_main.xml layout on the screen, the MethAndroid action code is going to look for the method defined in the android:onClick attribute here. The action code is going to look for a method in the following format.

Complete code MainActivity.class

 Let’s run “Android Simple Button Example now”!

android button example

 Download Android button example Source code :

Leave a Reply