Monday, October 16, 2017

Android: EditText on Button Click & Toggle Button


Objective: 
The objective of this Android tutorial is to use Android EditText to enter some value and display the same in TextView on button click. Also to use the ToggleButton and on-click should display the pop-up message using Toast. Refer the screen shots below.

Screenshots:
1. Default Home page will display the TextView, EditText with hint “Enter anything here”, Button and Togglebutton (with OFF state).


2. Enter some text (Test in the screenshot below), click the Green Tick mark in the keypad (as highlighted in red below) and click the Button (as highlighted in yellow), it should now display the entered text (Test here) in the TextView area.



3. Now click the Toggle button “OFF”, it will display the Toast message “OFF” below.



4. Now click the Toggle button “ON”, it will display the Toast message “ON” below.


Instructions to setup:
1. Git clone the project and you should see the project \4_Toggle_Button_N_EditText_On_Button_Click downloaded
2. Now open the project in Android Studio
3. Press the keyboard – Shift + F10 to run the App, select the configured virtual device and click OK.

4. You can now see the output in the Android Emulator.

Source Code Explanation:
1. Activity_main.xml ((under \src\res\layout\):
1. Overall Layout is set as "RelativeLayout"
2. TextView component is set with:
id as "textView"
3. EditText component is set with:
id as "editText"
hint as "Enter anything here.."

Cont..
4. Button component is set with:
id as "button"
text as "Button”
5. Toggle Button component is set with:
id as "toggleButton"


2. MainActivity.java:
1. Instantiate TextView, EditText, Button by using findViewById() by passing their respective id’s as defined in activity_main.xml
2. Set On-click listener function for the button and onClick get the text entered from EditText (using getText.toString()) and set it to TextView (setText()) as shown in the code below.
3. Instantiate ToggleButton by using findViewById() by passing the respective id of ToggleButton as defined in activity_main.xml
4. Now invoke the setOnCheckedChangedListenter() function, which accepts a boolean parameter isChecked, which will be true if the ToggleButton is in ON state and will be false, if the ToggleButton is in OFF state.
5. If the isChecked is true, set the Toast text to ON, else set the Toast text to OFF.

3. colors.xml (under \src\res\values\):
Default standard colors defined

4. strings.xml (under \src\res\values\)
All string values defined

5. styles.xml (under \src\res\values\)
All the default styles defined.



No comments:

Post a Comment