Problem
I have an XML layout used by 2 activities. Within this layout, there’s a view that is visible
for Activity1
and gone
for Activity2
. Activity1
is used more times compared to Activity2
. I would like to know which of the following methods is a better practice, if there’s a better one.
Method 1: The view is gone
and it’s turned visible
with every instance of the Activity1
.
XML:
<View android_id="@+id/myView" android_visibility="gone" />
Java:
class Activity1 extends Activity {
((View) findViewById(R.id.myView)).setVisibility(0);
}
class Activity2 extends Activity {
}
Method 2: The view is visible
and it’s turned gone
only when Activity2
is being used.
XML:
<View android_id="@+id/myView" android_visibility="visible" />
Java:
class Activity1 extends Activity {
}
class Activity2 extends Activity {
((View) findViewById(R.id.myView)).setVisibility(8);
}
So, is it better to change the visibility programmatically multiple times or fewer times?
Solution
According to View source code setting visibility through xml (line 3450) is cheaper than through setVisibility
method (line 5511).
So it is better to change visibility programmatically fewer times.
You should never use “magic numbers” in your code, otherwise code is unreadable.
setVisibility(0)
looks like you are hiding the view, while the truth is opposite.
Always use constants (View.GONE
and View.VISIBLE
in this case).