我正在做 Android Studio Java 应用程序的用户界面。我使用指南通过布局约束来约束元素,例如: app:layout_constraintEnd_toStartOf="@+id/vButtonGuidelineEnd"
我想在不同的布局中使用相同的指南(将它们视为边距)。有没有办法不重复代码。除了创建许多准则(完全相同)之外,它们还必须具有不同的名称。它没有任何意义。我进行了很多搜索,但没有找到一种方法可以做到这一点。人们解释了在单一布局中使用的指南。
我尝试使用所有通用准则创建一个布局,称为Guidelines.xml,这是另一个约束布局。这是有道理的。我尝试以某种方式将此布局包含到其他布局中,但它像块一样包含在内,并且我无法访问guidelines.xml 布局的元素。因此,我不能将元素限制在给定的指导方针内。这是我的guidelines.xml:
<?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" android:id="@+id/guidelinesLayout" android:layout_width="match_parent" android:layout_height="match_parent">
<androidx.constraintlayout.widget.Guideline
android:id="@+id/vButtonGuidelineStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.2" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/vButtonGuidelineEnd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.8" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/hIconGuidelineStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.05" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/hIconGuidelineEnd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.3" /></androidx.constraintlayout.widget.ConstraintLayout>`
我想在几种布局中使用这个不同的准则。例如,在另一个布局中执行类似的操作,但使用guidelines.xml的指导方针:
<TextView
android:id="@+id/textViewAppName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"
android:textAppearance="@style/LargeTextAppearance"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.494"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/hIconGuidelineEnd" ***
app:layout_constraintVertical_bias="0.0" />
您将需要使用样式来跨多个对象复制共同特征。这将避免代码重复,并允许您根据需要更快地进行更改。您将创建一个
styles.xml
文件并命名要使用的样式,然后设置其所有实例中通用的特定属性。该文档可以在这里找到:
https://developer.android.com/develop/ui/views/theming/themes#Styles