Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Contact us
Hide Buttons

First Android Application — Part 2

In my pre­vi­ous arti­cle “First android Appli­ca­tion” you have learnt about–

Now we will extend it further,

How about Text will get dis­played on the Click of a button.

Steps:

  • Cre­ate a button.
  • Hide the text
  • Cre­ate a onClick method for the button.
  • Add the code to dis­play the text in the onClick().

Cre­ate a but­ton.

Open the activity_main.xml file and add the below code.

Add a new String in String.xml

<Button

android:id="@+id/Button01"

android:layout_width="wrap_content"

android:layout_height="wrap_content"/>

Save the project and run it.

Blank Button display

Blank But­ton display

As you can see that but­ton is dis­played but it has no text. Lets add proper text to it.

Add a String resource with Name: “show_me_button” and Value Show Me The Text” . To know more about , how to add a string resource, Click here “Strings.xml”

Now add this String resource in the main_activity.xml file.

Add android:text=”@string/show_me_button to the xml file. After adding it your XML file will looks like the below picture,

activity_main xml file

activity_main xml file

Save the project and run it.

Button display

But­ton display

Now we have the but­ton, lets hide the text first then we will write the code for dis­play­ing the text in the onClick func­tion of the button.

To hide the text, we have the prop­erty called “visibility”

add android:visibility = “invis­i­ble” inside the TextView, Now you TextView will look like this

<TextView

android:id="@+id/TextView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/hello_world"

android:visibility = "invisible" />

save and run the application.

Hidden text

Hid­den text

Now our text is hid­den, Lets cre­ate onClick event for the button.

Add android:onClick = “Show­Text” in But­ton Tag, now But­ton tag will look like this,

<Button

android:id="@+id/Button01"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/show_me_button"

android:onClick = "ShowText" />

Now we need to cre­ate a func­tion called Show­Text() in the Main_Activity.java file, so open it add the fol­low­ing code into it.

import android.view.View;

public void ShowText(View v){

       TextView tv = (TextView) findViewById(R.id.TextView01);

       tv.setVisibility(View.VISIBLE);

}

save and run the application.

Show Text on Click

Show Text on Click

Happy Android­ing 🙂
Sumit Jain

You may also like...

Leave a Reply

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