Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide layouts / views programmatically in Android

I have just started learning Android. Few confusions I have regarding layouts in XML

  1. Are all views that I define in my layout are essentially inflated or they are optional? Suppose I have two different views in a view-group but I want to use only first or only second conditionally. Is it possible?

  2. How dynamically created views deal with layout.XML file?

  3. If I want received messages to be shown in red and sent messages in black how can I do that?

like image 985
Shrangi Tandon Avatar asked Apr 04 '15 17:04

Shrangi Tandon


People also ask

How to hide views in android?

Tap on the three vertical dots (Android) or three horizontal dots (iPhone) in the top right of your post. Tap 'Hide Like Counts' or 'Hide Like and View Counts' to turn on the setting.

How do you hide layout?

You can also set the visibility in your layout. xml if you want it hidden when your application first starts. android:visibility="gone" should do the trick. This way it is hidden from the very start when the layout is initialized by your app.

How do I hide a view?

Use with setVisibility(int) and android:visibility . This view is invisible, and it doesn't take any space for layout purposes.


1 Answers

You can include views in the XML layout file that are invisible until you programatically display them. Just use "android:visible="gone" or "android:visible="invisible" in the XML file.

For instance, I include the following in my layout file initially but it's not visible:

    <LinearLayout
        android:id="@+id/pnlLatLong"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:visibility="gone"
        >
        <TextView
            android:id="@+id/lblLatLng"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/lat_long"
            />
        <EditText
            android:id="@+id/txtLatitude"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="numberDecimal|numberSigned"
            />
        <EditText
            android:id="@+id/txtLongitude"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="numberDecimal|numberSigned"
            />
    </LinearLayout>

In Java code, when the code logic dictates it should be visible, I change the visibility programatically to:

    View v = findViewById(R.id.pnlLatLng);
    v.setVisibility(View.VISIBLE);
like image 96
Kyus Addiction Avatar answered Oct 26 '22 22:10

Kyus Addiction