Русские Блоги
Разница между атрибутами видимости VISIBLE, INVISIBLE и GONE в Android
В разработке для Android большинство элементов управления имеют атрибут видимости, а есть три атрибута: «видимый», «невидимый» и «пропавший». В основном используется для настройки отображения и скрытия элементов управления. Некоторые люди могут задаться вопросом, в чем разница между невидимым и ушедшим? ? ? Итак, с этим вопросом мы смотрим на следующее:
Это устанавливается следующим образом в файле XML и коде Java:
Видимый (видимый)
XML-файл: android: visibility = «visible»
Java-код: view.setVisibility (View.VISIBLE);
Невидимый (невидимый)
XML-файл: android: visibility = «invisible»
Java-код: view.setVisibility (View.INVISIBLE);
Спрятаться
XML-файл: android: visibility = «ушел»
Java-код: view.setVisibility (View.GONE);
Чтобы различить три, я построил Купол для демонстрации, сначала перейдем к кодексу Купола, после демонстрации я знаю разницу между ними:
- xml version = «1.0» encoding = «utf-8» ?>
- LinearLayout xmlns:android = «http://schemas.android.com/apk/res/android»
- android:layout_width = «fill_parent»
- android:layout_height = «fill_parent»
- android:orientation = «vertical» >
- LinearLayout
- android:layout_width = «fill_parent»
- android:layout_height = «wrap_content»
- android:orientation = «horizontal»
- android:layout_marginBottom = «20dip» >
- TextView
- android:layout_width = «wrap_content»
- android:layout_height = «wrap_content»
- android:layout_weight = «1»
- android:background = «#F00»
- android:text = «TextView1»
- android:textSize = «23sp»
- android:visibility = «visible»/>
- TextView
- android:id = «@+id/mainTV2»
- android:layout_width = «wrap_content»
- android:layout_height = «wrap_content»
- android:layout_weight = «1»
- android:background = «#00F»
- android:text = «TextView2»
- android:textSize = «23sp»
- android:visibility = «visible»/>
- LinearLayout >
- Button
- android:id = «@+id/mainBtn1»
- android:layout_width = «fill_parent»
- android:layout_height = «wrap_content»
- android:text = «TextView2 ВИДИМ»
- android:onClick = «mianOnClickListener»/>
- Button
- android:id = «@+id/mainBtn2»
- android:layout_width = «fill_parent»
- android:layout_height = «wrap_content»
- android:text = «TextView2 невидим»
- android:onClick = «mianOnClickListener»/>
- Button
- android:id = «@+id/mainBtn3»
- android:layout_width = «fill_parent»
- android:layout_height = «wrap_content»
- android:text = «TextView2 ушел»
- android:onClick = «mianOnClickListener»/>
- LinearLayout >
Пока последние три кнопки являются атрибутами, которые контролируют видимость TextView
- package com.chindroid.visibility;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.TextView;
- public class MainActivity extends Activity <
- /** TextView2 */
- private TextView mainTV2 = null ;
- @Override
- public void onCreate(Bundle savedInstanceState) <
- super .onCreate(savedInstanceState);
- setContentView(R.layout.main);
- // Инициализируем данные
- initData();
- >
- / ** Метод инициализации контроля * /
- private void initData() <
- mainTV2 = (TextView)findViewById(R.id.mainTV2);
- >
- /**
- Метод реагирования на событие нажатия кнопки в MainActivity
- *
- * @param v
- */
- public void mianOnClickListener(View v) <
- switch (v.getId()) <
- case R.id.mainBtn1: < // Событие ответа кнопки 1
- // Установить TextView2 как видимый
- mainTV2.setVisibility(View.VISIBLE);
- break ;
- >
- case R.id.mainBtn2: < // Событие ответа кнопки 2
- // Установить TextView2 как невидимый
- mainTV2.setVisibility(View.INVISIBLE);
- break ;
- >
- case R.id.mainBtn3: < // Ответное событие кнопки 3
- // Установить TextView2, чтобы скрыть
- mainTV2.setVisibility(View.GONE);
- break ;
- >
- default :
- break ;
- >
- >
- >
При запуске программы оба TextViews видны
Когда мы нажимаем первую кнопку и устанавливаем для свойства TextView2visibility значение INVISIBLE, процедура выглядит следующим образом:
Когда мы нажимаем третью кнопку и устанавливаем свойство TextView2visibility в GONE, процедура выглядит следующим образом:
Когда мы снова нажмем первую кнопку и установим свойство TextView2visibility в VISIBLE, TextView2 снова будет представлен, как показано на следующем рисунке:
VISIBLE: сделать элемент управления видимым
Невидимый: установите элемент управления невидимым
GONE: установить контроль, чтобы скрыть
Основное различие между INVISIBLE и GONE заключается в следующем: когда свойство видимости элемента управления равно INVISIBLE, интерфейс резервирует пространство, занимаемое элементом управления view, а когда свойство элемента управления равно GONE, интерфейс не сохраняет пространство, занимаемое элементом управления view.
Источник
IntDef and StringDef in Android
We often use View ’s visibility in our apps to show and hide them. We use void setVisibility(int visibility) method for that purpose. But have you ever thought that why this method always takes VISIBLE , INVISIBLE and GONE rather than any int value like 0 or 1 etc.? Although method’s parameter type is int , then why it doesn’t accept the direct numbers or any other int variable except those three.
In java, enum is known concept, and in many cases you can use it, but for android, enum is something you should avoid to use as it’s processing performance is not efficient, so in Android performance patterns it’s told to avoid enum s and to use annotations like @IntDef and @StringDef .
For example, you are working on a library that make user choose photo from gallery and camera and you are passing int value in your library method and taking argument in int . Then, based upon that value, you are opening camera or gallery.
We can create static final int variables with names like CAMERA = 0 and GALLERY = 1 to make things easier to read and understand, but that will still give developers to pass any kind of int value in the pickPhoto() method. But, our goal is to restrict the developers to only pass values through our assigned names as its happening with View.setVisibility() method.
For this purpose, android has @IntDef and @StringDef annotations. Here’s a simplest example how previously described problem can be made easy with @IntDef .
The important topic here to understand is why we are not using enum s? Although you can use it for similar purposes but they are not as memory efficient as static final int constants. Here’s a nice video of performance optimization discussing the similar topic by Google below.
If you liked this article, you can read my new articles below:
Adding Padding in Tabs in Android
In the app, which I am making at my job, I had a situation where I needed a huge number of tabs with the Fragment View Pager.
May 2, 2018
Live Code Templates in Android Studio
Code completion can improve your productivity by reducing how much you have to type, but there are situations when a more powerful tool is needed. Thanks to Android Studio and IntelliJ, live templates make it much easier to focus on just the things you care about.
May 2, 2018
7 years experience. 💻 Creator of various Open Source libraries on Android . 📝 Author of two technical books and 100+ articles on Android. 🎤 A passionate Public Speaker giving talks all over the world.
Источник
Русские Блоги
Разница между атрибутами видимости VISIBLE, INVISIBLE и GONE в Android
В разработке для Android большинство элементов управления имеют атрибут видимости, а есть три атрибута: «видимый», «невидимый» и «пропавший». В основном используется для настройки отображения и скрытия элементов управления. Некоторые люди могут задаться вопросом, в чем разница между невидимым и ушедшим? ? ? Итак, с этим вопросом мы смотрим на следующее:
Это устанавливается следующим образом в файле XML и коде Java:
Видимый (видимый)
XML-файл: android: visibility = «visible»
Java-код: view.setVisibility (View.VISIBLE);
Невидимый (невидимый)
XML-файл: android: visibility = «invisible»
Java-код: view.setVisibility (View.INVISIBLE);
Спрятаться
XML-файл: android: visibility = «ушел»
Java-код: view.setVisibility (View.GONE);
Чтобы различить три, я построил Купол для демонстрации, сначала перейдем к кодексу Купола, после демонстрации я знаю разницу между ними:
- xml version = «1.0» encoding = «utf-8» ?>
- LinearLayout xmlns:android = «http://schemas.android.com/apk/res/android»
- android:layout_width = «fill_parent»
- android:layout_height = «fill_parent»
- android:orientation = «vertical» >
- LinearLayout
- android:layout_width = «fill_parent»
- android:layout_height = «wrap_content»
- android:orientation = «horizontal»
- android:layout_marginBottom = «20dip» >
- TextView
- android:layout_width = «wrap_content»
- android:layout_height = «wrap_content»
- android:layout_weight = «1»
- android:background = «#F00»
- android:text = «TextView1»
- android:textSize = «23sp»
- android:visibility = «visible»/>
- TextView
- android:id = «@+id/mainTV2»
- android:layout_width = «wrap_content»
- android:layout_height = «wrap_content»
- android:layout_weight = «1»
- android:background = «#00F»
- android:text = «TextView2»
- android:textSize = «23sp»
- android:visibility = «visible»/>
- LinearLayout >
- Button
- android:id = «@+id/mainBtn1»
- android:layout_width = «fill_parent»
- android:layout_height = «wrap_content»
- android:text = «TextView2 ВИДИМ»
- android:onClick = «mianOnClickListener»/>
- Button
- android:id = «@+id/mainBtn2»
- android:layout_width = «fill_parent»
- android:layout_height = «wrap_content»
- android:text = «TextView2 невидим»
- android:onClick = «mianOnClickListener»/>
- Button
- android:id = «@+id/mainBtn3»
- android:layout_width = «fill_parent»
- android:layout_height = «wrap_content»
- android:text = «TextView2 ушел»
- android:onClick = «mianOnClickListener»/>
- LinearLayout >
Пока последние три кнопки являются атрибутами, которые контролируют видимость TextView
- package com.chindroid.visibility;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.TextView;
- public class MainActivity extends Activity <
- /** TextView2 */
- private TextView mainTV2 = null ;
- @Override
- public void onCreate(Bundle savedInstanceState) <
- super .onCreate(savedInstanceState);
- setContentView(R.layout.main);
- // Инициализируем данные
- initData();
- >
- / ** Метод инициализации контроля * /
- private void initData() <
- mainTV2 = (TextView)findViewById(R.id.mainTV2);
- >
- /**
- Метод реагирования на событие нажатия кнопки в MainActivity
- *
- * @param v
- */
- public void mianOnClickListener(View v) <
- switch (v.getId()) <
- case R.id.mainBtn1: < // Событие ответа кнопки 1
- // Установить TextView2 как видимый
- mainTV2.setVisibility(View.VISIBLE);
- break ;
- >
- case R.id.mainBtn2: < // Событие ответа кнопки 2
- // Установить TextView2 как невидимый
- mainTV2.setVisibility(View.INVISIBLE);
- break ;
- >
- case R.id.mainBtn3: < // Ответное событие кнопки 3
- // Установить TextView2, чтобы скрыть
- mainTV2.setVisibility(View.GONE);
- break ;
- >
- default :
- break ;
- >
- >
- >
При запуске программы оба TextViews видны
Когда мы нажимаем первую кнопку и устанавливаем для свойства TextView2visibility значение INVISIBLE, процедура выглядит следующим образом:
Когда мы нажимаем третью кнопку и устанавливаем свойство TextView2visibility в GONE, процедура выглядит следующим образом:
Когда мы снова нажмем первую кнопку и установим свойство TextView2visibility в VISIBLE, TextView2 снова будет представлен, как показано на следующем рисунке:
VISIBLE: сделать элемент управления видимым
Невидимый: установите элемент управления невидимым
GONE: установить контроль, чтобы скрыть
Основное различие между INVISIBLE и GONE заключается в следующем: когда свойство видимости элемента управления равно INVISIBLE, интерфейс резервирует пространство, занимаемое элементом управления view, а когда свойство элемента управления равно GONE, интерфейс не сохраняет пространство, занимаемое элементом управления view.
Источник