After testing the basic environment of the Android SDK , its time to start fiddling around with some cool user interactions provided by Android.
In this post I will demonstrate using Android widgets such as Buttons and TextViews.
Just be patient and follow the steps below:
1. Create a new Android Application Project
- Go to File > New > Android Application Project.
- Give a name to your app and proceed forward as in the last post (First App).
- Remember to select an Empty Activity in activity type.
|Naming the app|
2. Open the activity_main.xml file
- Open the activity_main.xml file from the Package Explorer , if not already open.
- This file is located res > layout folder under your project in Package Explorer.
3. Add Button and TextView
- Remove the TextView showing "Hello World" by selecting it and pressing Delete.
- Now in the Palette click on From Widgets tab and drag and drop a button to the Graphical Layout.
- Re-size and re-position it any way you like.
- Similarly drag and drop a TextView (Large Text or any other) to the Graphical Layout.
- You can tinker around with the self generated xml code by clicking on the activity_main.xml tab at the bottom of the eclipse window.
4. Open the MainActivity.java file
- If not already open, go to Package Explorer and under your project go to src > (Package Name) > MainActivity.java.
- Copy the java code below to your MainActivity.java (Remember to change the package name to your package name).
5. Run the Application
- Build and run the app by pressing CTRL + F11 or click Run > Run.
- Remember to configure AVD as shown in previous post or connect your own device to install and run the app.
On Button Click
- The first few lines of the code has some import statements which are auto included or can be included by clicking on error suggestions popups on the left of the code window.
- Our main activity is that class which has the main GUI thread. Its the first screen which the user sees when the app is launched. In this example, the main activity extends ActionBarActivity to suggest that it shows an action bar on the top of the app with and methods OnCreateOptionsMenu creates the list icon on the right of the action bar.
- In out MainActivity class we create two private variables my_button & my_textView to point out button and textview in our xml file (activity_main).
- The method OnCreate is called when the Android system wants to draw something related to the app on the main screen.
- The OnCreate method first sets the view of the app to activity_main.xml by callins setContentView(R.layout.activity_main);
- The we bind our variables my_button & my_textView to corresponding id's in main xml file.
7. Next we bind a event listener to our button which is called when the user clicks it.
8. Here we set the text of the TextView to whatever we want.