Question
How can I hide a View in Android programmatically during an activity result?
if(!mUseVolumeButtonAsPTT){
bottomLinearLayout.setVisibility(View.GONE);
} else {
bottomLinearLayout.setVisibility(View.VISIBLE);
}
Answer
This guide will walk you through the steps to programmatically hide and show a View, specifically a `LinearLayout`, when returning from an activity in an Android application.
// Hiding the bottom LinearLayout based on the boolean value passed from the menu activity.
if(resultData.getBoolean("UseVolumeButtonAsPTT")) {
bottomLinearLayout.setVisibility(View.VISIBLE); // Show
} else {
bottomLinearLayout.setVisibility(View.GONE); // Hide
}
Causes
- Not correctly referencing the layout to be hidden or shown.
- Confusion between `View.GONE` and `View.INVISIBLE`.
- Failing to call `setVisibility()` method on the right UI thread.
Solutions
- Use the `setVisibility(View.GONE)` method to hide a View and `setVisibility(View.VISIBLE)` to show it.
- Ensure you're referencing the correct `LinearLayout` IDs when calling `findViewById()` method.
- Invoke UI updates on the main (UI) thread by using `runOnUiThread()` if updating from a background thread.
Common Mistakes
Mistake: Using `setVisibility(View.INVISIBLE)` instead of `View.GONE`.
Solution: Use `View.GONE` to remove the view from the layout, allowing other views to move up.
Mistake: Not calling `setVisibility()` on the UI thread leading to no change in the layout.
Solution: Use `runOnUiThread()` to ensure layout changes are executed on the main thread.
Helpers
- android hide view programmatically
- setVisibility in android
- LinearLayout visibility android
- hide show view in activity result