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 previous article “First android Application” you have learnt about-

Now we will extend it further,

How about Text will get displayed on the Click of a button.

Steps:

  • Create a button.
  • Hide the text
  • Create a onClick method for the button.
  • Add the code to display the text in the onClick().

Create a button.

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 Button display

As you can see that button is displayed 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

Button display

Now we have the button, lets hide the text first then we will write the code for displaying the text in the onClick function of the button.

To hide the text, we have the property called “visibility”

add android:visibility = “invisible” 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

Hidden text

Now our text is hidden, Lets create onClick event for the button.

Add android:onClick = “ShowText” in Button Tag, now Button 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 create a function called ShowText() in the Main_Activity.java file, so open it add the following 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 Androiding 🙂
Sumit Jain

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.

You may also like...

Leave a Reply

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