Переключать видимость группы цепей в макете ограничения
В предыдущем макете xml у меня есть несколько групп представлений с несколькими элементами внутри. Скрыть каждую группу представлений также скрыть все дочерние элементы. Поскольку я хотел иметь плоскую структуру и пробовал ConstraintLayout. Прохладный Я знаю, как цепной элемент с распространением правильно выровнять. Поскольку плоская структура не обернута LinearLayout, теперь у меня есть 3 вида, чтобы спрятаться. Я хотел бы знать, есть ли альтернатива для достижения этого.
Без компоновки ограничений
<RelativeLayout....
..........
..........
<LinearLayout
android:visibility="gone"
tools:visibility="visible"
android:id="@+id/filter_area"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.AppCompatTextView
android:id="@+id/lblTerminal"
android:background="@color/lightGray"
style="@style/PurpleSubtitle"
android:drawableRight="@drawable/i_down_yellow"
android:drawableEnd="@drawable/i_down_yellow"
android:padding="10dp"
android:text="@string/lblTerminal"
android:layout_weight="5"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<View
android:background="@android:color/black"
android:layout_width="1dp"
android:layout_height="match_parent"/>
<android.support.v7.widget.AppCompatTextView
android:id="@+id/lblCategory"
android:background="@color/lightGray"
android:padding="10dp"
android:drawableRight="@drawable/i_down_yellow"
android:drawableEnd="@drawable/i_down_yellow"
style="@style/PurpleSubtitle"
android:text="@string/lblCategory"
android:layout_weight="5"
android:layout_width="0dp"
android:layout_height="wrap_content" />
</LinearLayout>
.......
.......
</RelativeLayout>
С макетом ограничений
<android.support.constraint.ConstraintLayout
.....
.....
.....
#happy that i no longer need LinearLayout for align properly
<android.support.v7.widget.AppCompatTextView
android:id="@+id/lblTerminal"
android:background="@color/lightGray"
style="@style/PurpleSubtitle"
android:drawableRight="@drawable/i_down_yellow"
android:drawableEnd="@drawable/i_down_yellow"
android:padding="10dp"
android:text="@string/lblTerminal"
android:layout_weight="5"
android:layout_width="0dp"
android:layout_height="50dp"
app:layout_constraintTop_toBottomOf="@+id/txt_search"
app:layout_constraintRight_toLeftOf="@+id/view3"
app:layout_constraintLeft_toLeftOf="@+id/guideline2"
app:layout_constraintHorizontal_chainStyle="spread"/>
<View
android:background="@android:color/black"
android:layout_width="1dp"
android:layout_height="50dp"
android:id="@+id/view3"
app:layout_constraintTop_toBottomOf="@+id/txt_search"
app:layout_constraintRight_toLeftOf="@+id/lblCategory"
app:layout_constraintLeft_toRightOf="@+id/lblTerminal" />
<android.support.v7.widget.AppCompatTextView
android:id="@+id/lblCategory"
android:background="@color/lightGray"
android:padding="10dp"
android:drawableRight="@drawable/i_down_yellow"
android:drawableEnd="@drawable/i_down_yellow"
style="@style/PurpleSubtitle"
android:text="@string/lblCategory"
android:layout_width="0dp"
android:layout_height="50dp"
app:layout_constraintTop_toTopOf="@+id/view3"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toRightOf="@+id/view3" />
......
......
......
</android.support.constraint.ConstraintLayout>
Ответы
Ответ 1
Да, так что теперь в ConstraintLayout
мы также можем управлять видимостью определенных групп видов, используя Group
Это новая функция, представленная в ConstraintLayout, которая в настоящее время находится в бета-версии.
Как добавить бета-версию ConstraintLayout
в ваш проект? Выполните следующие действия:
Добавьте поддержку maven в файл проекта gradle, как показано ниже
allprojects {
repositories {
maven { url 'https://maven.google.com' }
jcenter()
}
}
Затем в зависимости gradle приложения добавьте зависимость библиотеки ConstraintLayout
compile 'com.android.support.constraint:constraint-layout:1.1.0-beta3'
Теперь вы должны добавить Group
в ваш ConstraintLayout
следующим образом
<android.support.constraint.Group
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:constraint_referenced_ids="button7,button3,button2"
android:id="@+id/group" />
Где в Group
ссылочный идентификатор...
app:constraint_referenced_ids="button7,button3,button2"
... содержит идентификатор представления, разделенный запятыми, который вы хотите обрабатывать во время выполнения, поэтому в Activity вы просто привязываете Group
, как показано ниже, и обрабатываете видимость
import android.support.constraint.Group; //import statement in activity
Group group=(Group)findViewById(R.id.group); //bind view from xml
group.setVisibility(View.VISIBLE); //this will visible all views
group.setVisibility(View.GONE); //this will set Gone to all views
group.setVisibility(View.INVISIBLE); //this will set INVISIBLE to all view
ОБНОВЛЕНИЕ: ConstraintLayout
1.1.0 стабильная версия была выпущена 12 апреля 2018 года https://androidstudio.googleblog.com/2018/04/constraintlayout-110.html
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
Редактировать для Android X: если кто-то использует пакет Android X, вы можете найти пакет информация здесь
https://developer.android.com/jetpack/androidx/migrate
Ответ 2
Если вы используете бета-версию ограничения ограничений, следуйте ответу @pavan
Если вы используете AndroidX, следуйте приведенным ниже инструкциям, чтобы интегрировать ограничение ограничений и группу:
1) Добавьте зависимость макета ограничения AndroidX в ваш проект:
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
2) Используйте ConstraintLayout Group, как показано ниже в вашем проекте:
<androidx.constraintlayout.widget.Group
android:id="@+id/groupDetails"
android:layout_width="wrap_content"
android:visibility="gone" // Default visibility for group views
app:constraint_referenced_ids="textViewUserName, ..." // id which you want to include in group
android:layout_height="wrap_content"/>
3) Вот часть кода для переключения видимости:
private lateinit var groupDetails:Group
...
groupDetails = findViewById(R.id.groupDetails)
groupDetails.visibility = View.GONE // Change visibility
Надеюсь, это поможет при использовании AndroidX.
Ответ 3
我 使用 的 版本 是 截止 到 目前 最新 的 版本, 依然 存在 这个 问题
androidx.constraintlayout:constraintlayout:2.0.0-alpha3
我 使用 官方 提供 的 API 来 解决 这个 问题
androidx.constraintlayout.widget.Group#updatePreLayout
как это
groupPwdLogin.setVisibility(View.VISIBLE);
groupPwdLogin.updatePreLayout(container);
Ответ 4
Вы можете использовать тот же Linear Layout, что и дочерний элемент макета Constraint Layout, или вы также можете сделать все эти 3 виджета в качестве дочернего объекта другого макета Constraint и сделать этот макет как дочерний элемент основного макета Constraint.
Затем вы можете сохранить видимость и другие вещи, как раньше.