6

I am trying to hide a RelativeLayout using setVisibility(View.GONE). But it is not working. Please check my code:

<LinearLayout>

    <RelativeLayout
        android:id="@+id/AccelerometerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView />
        <TextView />
        <TextView />
        <ImageView />

    </RelativeLayout>
</LinearLayout>

And I am using the following code for changing the visibility:

private RelativeLayout tv;
tv = (RelativeLayout) findViewById(R.id.AccelerometerView);
tv.setVisibility(View.GONE);

Is my approach correct? I know we can hide TextViews like this individually. but I want to hide all three TextViews and the ImageView collectively in a single command. Is there any other way?

Lamorak
  • 10,957
  • 9
  • 43
  • 57
Mohsin Anees
  • 698
  • 2
  • 9
  • 25

3 Answers3

6

You can create methods to alter the visibility of the layout tv dynamically. Set the layout to whatever visibility you require at start up.

I have included checks here, as it was part of some other code and may prove useful if you ever want to include a boolean check on visibility.

Declare your view in the body of your activity, so it can be accessed by any methods.

Activity:

RelativeLayout tv;

Oncreate:

tv = (RelativeLayout) findViewById(R.id.AccelerometerView);

Use these methods to control the visibility.

Not within create:

public void setLayoutInvisible() {
    if (tv.getVisibility() == View.VISIBLE) {
        tv.setVisibility(View.GONE);
    }
}
public void setLayoutVisible() {
    if (tv.getVisibility() == View.GONE) {
        tv.setVisibility(View.VISIBLE);
    }
}

Use GONE if you don't want the other elements displaced by an INVISIBLE element. You can use this principle for most things.

http://developer.android.com/reference/android/view/View.html

5

Ok, so as far as default behavior is concerned, setVisibility works on all subviews as well.

Try using

android:visibility="gone"

in the the xml within the RelativeLayout tag. If the view still shows up then it is being changed in the code somewhere. Post the complete code so maybe we can help.

dejavu89
  • 754
  • 1
  • 7
  • 17
3

Your code must work, but try to set layout visibility from xml attributes

<RelativeLayout
android:id="@+id/AccelerometerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone>
Hank Moody
  • 354
  • 2
  • 15