Skip to main content

How to set the visibility of a TextView in Kotlin Android

How to set the visibility of a TextView in Kotlin Android.

Here is a step-by-step tutorial on how to set the visibility of a TextView in Kotlin for Android:

Step 1: Create a new Android project Start by creating a new Android project in Android Studio. Choose an appropriate name and package for your project.

Step 2: Design the layout Open the activity_main.xml file from the res/layout directory. Add a TextView element to the layout by adding the following code:

<TextView
android:id="@+id/myTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!" />

Step 3: Get a reference to the TextView In the MainActivity.kt file, add a property to hold a reference to the TextView. Add the following code inside the onCreate method:

val myTextView = findViewById<TextView>(R.id.myTextView)

Step 4: Set the visibility To set the visibility of the TextView, you can use the visibility property. There are three possible values:

  • View.VISIBLE: The view is visible.
  • View.INVISIBLE: The view is invisible, but it still takes up space in the layout.
  • View.GONE: The view is invisible and does not take up any space in the layout.

To set the visibility to View.VISIBLE, use the following code:

myTextView.visibility = View.VISIBLE

To set the visibility to View.INVISIBLE, use the following code:

myTextView.visibility = View.INVISIBLE

To set the visibility to View.GONE, use the following code:

myTextView.visibility = View.GONE

Step 5: Test the visibility To test the visibility changes, you can add buttons or other UI elements to your layout. Add the following code to the activity_main.xml file to create two buttons:

<Button
android:id="@+id/showButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show" />

<Button
android:id="@+id/hideButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hide" />

Step 6: Handle button clicks In the MainActivity.kt file, add click listeners to the buttons to handle visibility changes. Add the following code inside the onCreate method:

val showButton = findViewById<Button>(R.id.showButton)
val hideButton = findViewById<Button>(R.id.hideButton)

showButton.setOnClickListener {
myTextView.visibility = View.VISIBLE
}

hideButton.setOnClickListener {
myTextView.visibility = View.GONE
}

Step 7: Run the app Run the app on an emulator or a physical device. Click the "Show" button to make the TextView visible, and click the "Hide" button to make it invisible.

That's it! You have successfully set the visibility of a TextView in Kotlin for Android.