Toggle visibility of a layout on onClick
12,445
Solution 1
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);
}
}
}
);
Solution 2
The another way of toggle, with less lines, if someone likes
// button to click
ImageButton properties = (ImageButton) findViewById(R.id.propBtn);
// and LinearLayout to toggle
final LinearLayout propLayout = (LinearLayout) findViewById(R.id.properLayout);
properties.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
propLayout.setVisibility((propLayout.getVisibility() == View.VISIBLE)
? View.INVISIBLE
: View.VISIBLE);
}
});
Author by
Lampione
Updated on June 04, 2022Comments
-
Lampione almost 2 years
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>