Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

How to Make a Button Invisible in Android?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

In many interactive applications, one of the purposes of the developer is to produce a satisfactory user experience. The more the screen consumed by the users, the more is the application grows. To achieve this, UX developers work hard on animations, selection of color palettes, etc. Moreover, good designs and animations attract users to use them more often. One subfield in this topic is playing animations and reflexes with the UI elements. Most of the beginners are unknown of the fact that they can create animations over the simple UI elements.

In this article, even we are disclosing with you an example of how you could make a UI element appear and disappear in Android. For that, start your IDE, and once you are set, follow the below steps.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Implement two-button, button 1 and button 2 as shown. When button 1 is clicked, button 2 will disappear.


<?xml version="1.0" encoding="utf-8"?>

Step 3: Working with the MainActivity.kt  file

In this code, initially, a variable temp is set to false. Now when the button is clicked, the code satisfies the if condition and makes the button invisible, and the temp value is reversed to true. Now if the button is clicked, the code would satisfy the else condition and make the button visible and assign temp to false.


import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.Toast
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        val mButton1 = findViewById<Button>(
        val mButton2 = findViewById<Button>(
        var temp = false
        mButton1.setOnClickListener {
                mButton2.visibility = View.INVISIBLE
                Toast.makeText(applicationContext, "Invisible", Toast.LENGTH_SHORT).show()
            } else {
                mButton2.visibility = View.VISIBLE
                Toast.makeText(applicationContext, "Visible", Toast.LENGTH_SHORT).show()
            temp = !temp

Note: These visibility attributes and functions apply to every UI element and need not necessarily be a button.


You can see that upon button 1 click, button 2 disappears.

My Personal Notes arrow_drop_up
Last Updated : 03 Jan, 2022
Like Article
Save Article
Similar Reads