Hiding objects in Android Studio is a task faced by both beginners and experienced developers. This could involve temporarily removing UI elements to test mockups, hiding sensitive data in code, or optimizing the display of components based on application logic. However, approaches to solving this problem differ radically depending on the type of object: it can be in XML markup, in code or even in the project structure. Visual element visual element in XML markup, software component V Kotlin/Java-code or even system file in the project structure.

In this article we will look at all the current methods of hiding objects - from basic methods like View.GONE to advanced techniques using Data Binding and customization AndroidManifest.xml. We will pay special attention to typical errors that lead to the application crashing or incorrect display of the interface. For example, many developers don't consider that a property takes up space in the markup while it removes the element from the layout completely. We'll also look at how to hide objects dynamically - depending on the Android version, screen resolution or user rights. visibility="invisible" takes up space in the markup, while gone removes the element from the layout completely. Weโ€™ll also look at how to hide objects dynamically, depending on the Android version, screen resolution, or user rights.

It is important to understand that some methods (for example, hiding system files through .gitignore) affect only your local copy of the project, while others (for example, conditional compilation with buildTypesaffect the final APK build). To avoid confusion, we have structured the material by type of object and provided practical examples for each case.

1. Hiding interface elements in XML markup

The most common scenario is hiding buttons, text fields or images directly in markup files (activity_main.xml, fragment_layout.xml etc.). For this purpose, Android Studio there are three main attributes:

  • ๐Ÿ”น android:visibility="visible" โ€” the element is displayed (default value).
  • ๐Ÿ”น android:visibility="invisible" โ€”the element is hidden, but takes up space in the markup (invisible, but affects layout).
  • ๐Ÿ”น android:visibility="gone" โ€” the element is completely removed from the layout (does not take up space).

An example of hiding a button in the markup:

<Button

android:id="@+id/myButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Press me"

android:visibility="gone" />

If you need to hide an element conditionally (for example, only on Android versions below 10), use Tools Attributes:

<TextView

android:id="@+id/warningText"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="This message is only visible on Android 10+"

tools:visibility="gone" />
โš ๏ธ Attention: Attribute tools:visibility works only in preview mode (Preview) c Android Studio and does not affect the final display in the application. To dynamically hide, use the code on Kotlin/Java.
๐Ÿ“Š Which method of hiding elements do you use more often?
XML attributes
app code (Kotlin/Java)
Data Binding
Other

2. Dynamically hiding objects in code (Kotlin/Java)

When hiding an element depends on application logic (for example, showing a button only to authorized users), you need to control visibility programmatically. In Kotlin this is done through the property visibility of the object View:

Basic syntax:

// Hide the element by taking up space

myButton.visibility = View.INVISIBLE

// Completely remove the element from the markup

myButton.visibility = View.GONE

// Return visibility

myButton.visibility = View.VISIBLE

Example with condition checking:

if (user.isPremium) {

premiumFeatureButton.visibility = View.VISIBLE

} else {

premiumFeatureButton.visibility = View.GONE

}

To simplify the code, you can use Kotlin extensions:

fun View.show() { visibility = View.VISIBLE }

fun View.hide() { visibility = View.INVISIBLE }

fun View.gone() { visibility = View.GONE }

// Usage:

myButton.gone() // instead myButton.visibility = View.GONE

โš ๏ธ Attention: When changing the visibility of elements frequently (for example, in RecyclerView), avoid calling findViewById in a loop. Cache links to View in ViewHolder to optimize performance.

The element is initialized (not null)|

Taking into account multithreading state (UI thread)|

Checking current visibility (avoid unnecessary operations)|

Exception handling when working with fragments-->

3. Hiding through Data Binding and ViewBinding

Modern approaches like Data Binding and ViewBinding allow you to control the visibility of elements more elegantly, without directly accessing View in the code. Let's look at both methods.

Method 1: ViewBinding (recommended by Google as a replacement findViewById):

// Enable ViewBinding in build.gradle (Module: app):

android {

...

buildFeatures {

viewBinding true

}

}

// Use in Activity/Fragment:

private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

binding = ActivityMainBinding.inflate(layoutInflater)

setContentView(binding.root)

// Hiding an element

binding.myButton.visibility = View.GONE

}

Method 2: Data Binding (two-way data binding):

<-- In markup (activity_main.xml) -->

<layout xmlns:android="http://schemas.android.com/apk/res/android">

<data>

<variable

name="viewModel"

type="com.example.MyViewModel"/>

</data>

<Button

android:id="@+id/myButton"

android:visibility="@{viewModel.isButtonVisible ? View.VISIBLE : View.GONE}"/>

</layout>

B ViewModel:

class MyViewModel : ViewModel() {

val isButtonVisible = MutableLiveData<Boolean>(false)

// Change the value to show/hide the button

}

Method Pros Cons When to use
findViewById Simplicity, works everywhere Probability of NPE, a lot of boilerplate code Small projects, rare operations with UI
ViewBinding Type safety, no NPE Requires configuration in build.gradle Modern projects (Google recommendation)
Data Binding Declarative approach, data binding Moderate to configure, affects build time Projects with MVVM/MVI, dynamic UI

4. Hiding system files and folders in the project

Sometimes you need to hide configuration files, API keys or temporary data from prying eyes directly in the project structure. Here are the main approaches:

  • ๐Ÿ“ Use .gitignore โ€” hides files from version control (Git), but they remain in the local project folder.
  • ๐Ÿ” Moving to res/values/secrets.xml โ€” for sensitive data (for example, API keys) that should not end up in the repository.
  • ๐Ÿ—ƒ๏ธ Creating custom buildTypes โ€”allows you to exclude files from the final APK build.

Example .gitignore for hiding local configs:

# Hide files with API keys

local.properties

*.keystore

secrets.properties

Hide IDE folders

.idea/

*.iml

build/

captures/

To hide files from the final build, add to build.gradle:

android {

buildTypes {

release {

// Exclude file from APK

aaptOptions {

ignoreAssetsPattern 'secret_*.json'

}

}

}

}

โš ๏ธ Attention: Files hidden through .gitignoreremain in the local project folder and can be accessed through the file manager. For complete security, use Android Secrets Gradle Plugin or store sensitive data in Firebase Remote Config.
How to completely remove a file from history Git?

If the file with secrets has already been committed, it must be deleted from the repository history:

1. Use the command git filter-branch or BFG Repo-Cleaner.

2. Update the remote repository with the flag --force.

3. Notify all team members about the need to clone the repository.

The operation is irreversible and may break the commit history!

5. Hiding components via AndroidManifest.xml

In some cases, you need to hide entire activities, services or content providers from the Android system. This is done through the app manifest using attributes android:enabled and android:exported.

Examples:

  • ๐Ÿšซ Disable activity (will not be visible in Task Manager):
<activity

android:name=".SecretActivity"

android:enabled="false" />

  • ๐Ÿ”’ Hide activity from other applications:
<activity

android:name=".InternalActivity"

android:exported="false" />

  • ๐Ÿ“ฑ Hide launcher icon (activity is not displayed in the application menu):
<activity

android:name=".MainActivity"

android:label="@string/app_name">

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

<activity

android:name=".HiddenActivity"

android:excludeFromRecents="true"

android:noHistory="true" />

The attribute android:excludeFromRecents="true" prevents activity from appearing in the list of recent applications, which is useful for login screens or temporary dialogs.

6. Advanced techniques: custom views and animations

For complex scenarios (for example, smooth hiding of an element with animation), standard methods are not enough. In such cases, use:

  • ๐ŸŽญ Animations AlphaAnimation or ObjectAnimator โ€”for a smooth disappearance.
  • ๐Ÿ–ผ๏ธ Custom View โ€”with an overridden method onDraw().
  • ๐Ÿ”„ Transition API โ€” for complex animations between states.

Example of fade animation:

val fadeOut = ObjectAnimator.ofFloat(myView, "alpha", 1f, 0f)

fadeOut.duration = 500 // 0.5 seconds

fadeOut.addListener(object : AnimatorListenerAdapter() {

override fun onAnimationEnd(animation: Animator) {

myView.visibility = View.GONE // Complete hiding after animation

}

})

fadeOut.start()

To create a completely invisible but clickable element (for example, for testing), you can use:

myView.apply {

alpha = 0f // Full transparency

isClickable = true // Preserve clickability

isFocusable = true

}

๐Ÿ’ก

If you need to hide the element only for screenshots (for example, to protect confidential data), use the flag View.SYSTEM_UI_FLAG_HIDE_NON_SYSTEM_OVERLAY_WINDOWS or override the method draw(canvas: Canvas) in a custom view, adding a check for screenshot mode.

7. Typical mistakes and how to avoid them

Even experienced developers make mistakes when working with object visibility. Here are the most common problems and their solutions:

Error Cause Solution
The element is not hidden after the call View.GONE The call is not in the UI thread or there is a conflict with animations Use runOnUiThread or post { view.gone() }
Crash with NullPointerException Trying to hide an uninitialized view Check for null or use ViewBinding
The element blinks when scrolling RecyclerView Frequent calls setVisibility in onBindViewHolder Cache the visibility state in the data model
Does not work tools:visibility in preview Missing namespace tools in the root tag Add xmlns:tools="http://schemas.android.com/tools"

Another common problem is incorrect behavior when rotating the screen. If you hide an element programmatically, its state is not preserved across configuration changes. Solution:

override fun onSaveInstanceState(outState: Bundle) {

super.onSaveInstanceState(outState)

outState.putBoolean("isButtonVisible", myButton.visibility == View.VISIBLE)

}

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

// ...

savedInstanceState?.let {

myButton.visibility = if (it.getBoolean("isButtonVisible")) View.VISIBLE else View.GONE

}

}

๐Ÿ’ก

Always test hiding elements on different versions of Android. For example, on Android 10+ the method View.GONE may behave differently due to changes in the layout system (ConstraintLayout 2.0).

FAQ: Frequently asked questions about hiding objects

Is it possible to hide an element so that it does not take up space, but remains clickable?

No, this contradicts the logic of Android. The property View.GONE completely removes the element from the layout and INVISIBLE leaves it unclickable. An alternative is to make the element transparent (alpha = 0f) and leave isClickable = true, but this can make testing more difficult.

How to hide an element only on a specific version of Android?

Use version checking in code:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {

myView.visibility = View.GONE // Hide on Android 10+

}

Or create separate layouts in folders res/layout-v29 (for Android 10).

Why does the layout get confused after hiding an element?

This happens because View.GONE removes an element from the hierarchy, and the remaining views are redistributed. Solutions:

  • Use ConstraintLayout with anchors (app:layout_constraint*).
  • Set fixed dimensions to the parent container.
  • Try Space or View s visibility="invisible" as a placeholder.
How to hide the system bar (status bar or navigation bar)?

Use system flags:

// Hide the status bar

window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN

// Hide the navigation bar (for immersive-mode)

window.decorView.systemUiVisibility = (

View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY

or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION

or View.SYSTEM_UI_FLAG_FULLSCREEN

)

Don't forget to add android:fitsSystemWindows="true" to the root ViewGroup.

Is it possible to hide an object so that it is visible only in the debug build?

Yes, use BuildConfig.DEBUG:

if (BuildConfig.DEBUG) {

debugInfoText.visibility = View.VISIBLE // Show only in debug

} else {

debugInfoText.visibility = View.GONE

}

Or create separate markups in folders src/debug/res and src/release/res.