Search code examples
javaandroidlayout

Toggle visibility of a layout on onClick


I need to set this layout visible when i click a button, my java is like:

Layout propLayout = (Layout) findViewById(R.id.properLayout);

    public void propsBtn(View view) {
propLayout.setVisiblity(View.Visible);
}

I know I'm totally wrong with the layout line! I'll be very grateful if someone could show me how to set it right :)

This is my XML:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/mainBackGround"
tools:context="com.myapplication2.app.MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="8dp">

...contents...

    </RelativeLayout>

</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="gone"
    android:id="@+id/properLayout">

    <RelativeLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:layout_gravity="bottom"
        android:padding="8dp">

...contents...           

    </RelativeLayout>

</LinearLayout>


Solution

  • DerGolem gave the right answer but he then deleted it, so I report it here now:

    //First we set visibility value of interested layout either to gone, visible or invisible
    android:visibility="gone"
    

    Then under onCreate write like:

    //specify the button that has to handle visibility  
    ImageButton properties = (ImageButton) findViewById(R.id.propBtn);
    
    //And the layout we want to change is visibility
    final LinearLayout propLayout = (LinearLayout) findViewById(R.id.properLayout);
    
    properties.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (propLayout.getVisibility() == View.VISIBLE){
                propLayout.setVisibility(View.INVISIBLE);
            } else {
                propLayout.setVisibility(View.VISIBLE);
            }
        }
    });