Как изменить visibility android

There is a way to change the visibility of View in the XML, but how can I change programmatically visibility of the layout defined in XML? How to get the layout object? <LinearLayout android...

There is a way to change the visibility of View in the XML, but how can I change programmatically visibility of the layout defined in XML? How to get the layout object?

<LinearLayout
    android:id="@+id/contacts_type"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:visibility="gone">
</LinearLayout>

asked Aug 12, 2010 at 8:15

Dariusz Bacinski's user avatar

Dariusz BacinskiDariusz Bacinski

8,2068 gold badges36 silver badges46 bronze badges

Have a look at View.setVisibility(View.GONE / View.VISIBLE / View.INVISIBLE).

From the API docs:

public void setVisibility(int visibility)

    Since: API Level 1

    Set the enabled state of this view.
    Related XML Attributes: android:visibility

Parameters:
visibility     One of VISIBLE, INVISIBLE, or GONE.

Note that LinearLayout is a ViewGroup which in turn is a View. That is, you may very well call, for instance, myLinearLayout.setVisibility(View.VISIBLE).

This makes sense. If you have any experience with AWT/Swing, you’ll recognize it from the relation between Container and Component. (A Container is a Component.)

answered Aug 12, 2010 at 8:18

aioobe's user avatar

aioobeaioobe

408k111 gold badges805 silver badges824 bronze badges

3

TextView view = (TextView) findViewById(R.id.textView);
view.setText("Add your text here");
view.setVisibility(View.VISIBLE);

Musa's user avatar

Musa

95.5k17 gold badges116 silver badges134 bronze badges

answered Jun 12, 2013 at 22:40

SuperNova1054's user avatar

Use this Layout in your xml file

<LinearLayout
  android:id="@+id/contacts_type"
  android:orientation="horizontal"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:visibility="gone">
</LinearLayout>

Define your layout in .class file

 LinearLayout linearLayout = (LinearLayout) findViewById(R.id.contacts_type);

Now if you want to display this layout just write

 linearLayout.setVisibility(View.VISIBLE);

and if you want to hide layout just write

 linearLayout.setVisibility(View.INVISIBLE);

Varun's user avatar

answered Nov 16, 2016 at 11:24

pavel's user avatar

pavelpavel

1,50420 silver badges19 bronze badges

You can change layout visibility just in the same way as for regular view.
Use setVisibility(View.GONE) etc. All layouts are just Views, they have View as their parent.

answered Aug 12, 2010 at 8:27

Konstantin Burov's user avatar

Konstantin BurovKonstantin Burov

68.7k16 gold badges114 silver badges93 bronze badges

this is a programatical approach:

 view.setVisibility(View.GONE); //For GONE
 view.setVisibility(View.INVISIBLE); //For INVISIBLE
 view.setVisibility(View.VISIBLE); //For VISIBLE

Mesalcode's user avatar

answered Sep 7, 2018 at 6:41

Hanisha's user avatar

HanishaHanisha

81910 silver badges8 bronze badges

Cover image for Android Views: Peek-A-Boo

Pabi Moloi, but Forbes

In this post, I will be talking about the Visibility attribute for Android views. So what are Android Views? Android Views are user interface elements that are drawn onto the screen and that a user can interact with. For example, a button, a textview,and an imageview.

Android view attributes define how an element looks like, such as it’s height, width, and color. Think of them as metadata for views. A view’s visibility can be set to gone, invisible, or visible, as indicated in the sample code below:
Visible Textview

android:visibility=»visible»
This is a view’s visibility value by default. This means that the view will always be displayed on the screen.
As it is default, a view’s visibility does not have to be explicitly set to visible. As we can see with the sample below, the textview that displays the infamous «Hello World» is visible on the screen.
Visible Textview

android:visibility=»gone»
When we set textview’s visibility attribute to gone,
it will simply not show on the screen and it’s space on the layout will be occupied by surrounding elements.
When the view is toggled from gone to visible, surrounding elements will simply make way for the view and the view will ocuppy it’s space and show on the screen.
Looking at our sample app below, we can see that the textview is not visible on the screen and it’s space is occupied by the buttons.
Visible Textview

android:visibility=»invisible»
If a view’s visibility is set to invisible, the view will not be displayed, but it will still occupy it’s space on a layout. So it might make the layout look a little weird with some extra space in-between elements.
Taking a look back at our sample app, the textview is not shown, but it still occupies it’s space. The buttons stay in their positions.
Visible Textview

Changing Visibility On The Go
Toggling between the different visibility values can be easily achieved programatically. I have added the functionality of toggling between the different visibility attribute value behind the clicks of the buttons. When the «Gone» button is clicked, we change the visibility value to gone. When the «Invisible» button is clicked, we change the visibility value to invisible. When the «Visible» button is clicked, we simply change the visibility value to visible.
Take a peek below:
Visible Textview

Toggling between the different visibility values aids us in showing the user relevant content depending on the activity being carried out on the screen. For example, we can show a loader when making a service call, and then only display the underlying content once we have a response from the server. The android visibility attribute is just one of many attributes that are available for us to use and play around with, so don’t be shy to try them out.
A cool post you can check out https://guides.codepath.com/android/Defining-Views-and-their-Attributes.

Credits:
Thank you to Andrei Lazarev for the amazing cover image take from https://unsplash.com/photos/U47vtNMkyXg

Read next


arafat4693 profile image

Advanced Google Search Techniques for Better Results😈

Arafat — Feb 3


naubit profile image

💻 7 Tips for Writing Clean and Efficient React Code

Al — Naubit — Feb 2


pulkit30 profile image

Docker Images: A Quick Guide

Pulkit Gupta — Jan 23


codewithvoid profile image

Should Developers Specialize or Generalize?

Void⚡ — Jan 24

Once unpublished, all posts by pabiforbes will become hidden and only accessible to themselves.

If pabiforbes is not suspended, they can still re-publish their posts from their dashboard.

Note:

Once unpublished, this post will become invisible to the public and only accessible to Pabi Moloi, but Forbes .

They can still re-publish the post if they are not suspended.

Thanks for keeping DEV Community 👩‍💻👨‍💻 safe. Here is what you can do to flag pabiforbes:

Make all posts by pabiforbes less visible

pabiforbes consistently posts content that violates DEV Community 👩‍💻👨‍💻’s
code of conduct because it is harassing, offensive or spammy.

Code

activity_main.xml:
We have two buttons and a text view. One button will set the visibility of text view to visible and the other will set the visibility of text view to invisible.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:background="@color/colorAccent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="My Visibility is changing"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="20dp"
        android:visibility="invisible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.732" />

    <Button
        android:id="@+id/show"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimaryDark"
        android:padding="10dp"
        android:text="Show Message"
        android:textColor="#fff"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.445" />

    <Button
        android:id="@+id/hide"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        android:padding="10dp"
        android:text="Hide Message"
        android:textColor="#fff"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.541" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Android Visibility Example"
        android:textColor="#000"
        android:textSize="24dp"
        app:layout_constraintBottom_toTopOf="@+id/show"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.496"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.9" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java:

package com.example.visibilityexample;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView textView;
    Button show, hide;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.textView);
        show = findViewById(R.id.show);
        hide = findViewById(R.id.hide);

        show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                textView.setVisibility(View.VISIBLE);
            }
        });

        hide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                textView.setVisibility(View.INVISIBLE);
            }
        });
    }
}

Output

The following are snapshots of the output.

That’s it for Android Visibility.

You can connect with me on Twitter for any discussion.

Thanks for reading.

Adios!

Если в xml создаю TextView там же указываю android:visibility=»gone», то после запуска TextView всё равно отображается. Почему?

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:visibility="gone" />

</androidx.constraintlayout.widget.ConstraintLayout>
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}


  • Вопрос задан

    более двух лет назад

  • 679 просмотров

В атрибутах корневого тега xml-файла указаны подключаемые пространства имен. В вашем случае:

xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"

Пространство имен tools как раз и необходимо для изменения вида только в редакторе. Используйте android:visibility="gone" для полноценного изменения отображения TextView.

В Android Studio рядом со значениями «только в редакторе» отображается значок в виде ключа.

5f7a36e063090850719004.png

Пригласить эксперта

Тут все правильно, стоило еще код приложить
попробуй добавить программно а с xml удали :

TextView kelErechApaim;
kelErechApaim = findViewById(R.id.kelErechApaim);
 kelErechApaim.setVisibility(View.GONE);


  • Показать ещё
    Загружается…

10 февр. 2023, в 13:40

75000 руб./за проект

10 февр. 2023, в 13:27

2000 руб./за проект

10 февр. 2023, в 13:18

150000 руб./за проект

Минуточку внимания

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Как изменить vin номер
  • Как изменить viewmodel css
  • Как изменить viewmodel cs go
  • Как изменить viewbox через css
  • Как изменить view sql

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии