# Change View visibility programmatically or through XML?

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?

-

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).

-
Constants are already implemented, I just prefer not to use them. The question was regarding a better methodology, not readability of code. –  slybloty Nov 14 '12 at 13:36
this is a codereview site ;). and i can just add that preference to not to use constants is very poor. –  Alex Nov 14 '12 at 17:20
That should be a comment, not an answer since it doesn't answer the question. –  slybloty Nov 14 '12 at 18:21
@slybloty - agree, you are right. –  Alex Nov 14 '12 at 22:31
@TrevorPilley I understand that you've edited my answer to make it look better. But probably you should not change code snippets in areas you are not too familiar about. On Android notation for constants is all-upper-case. And there is no need for some "ViewVisibility" since needed constants defined within SDK View class, as was shown in my answer initially –  Alex Nov 14 '12 at 22:37