TL; DR
Я хочу выровнять по центру ImageButton
в ScrollView
, и я очень доволен результатом в портретном режиме.Однако я не могу сказать то же самое для ландшафтного режима, и любая помощь будет принята с благодарностью.
Но позвольте мне объяснить
Я использую два файла макета здесь;первый - тот, который я использую для моего MainActivity
класса, называется activity_main.xml
.Второй (называемый fragment_main.xml
) вкладывается в activity_main.xml
, когда MainActivity
загружает MainFragment
.
Предварительный просмотр для fragment_main.xml
выглядит довольно многообещающе для портретного и ландшафтного режима: фрагмент_основной.xml в альбомной ориентации фрагмент_основной.xml в портретной области
И рендеринг activity_main.xml
в портретном режиме выглядит так, как я хочу, чтобы он выглядел: activity_main.xml в портрете
Однако activity_main.xml
в альбомном режиме выглядит странно, и я не могу понять, почему: activity_main.xml в альбомной ориентации
ЗдесьXML-код activity_main.xml
с fragment_main.xml
объединен в него как дочерний элемент ScollView
:
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:titleTextAppearance="@style/Toolbar.TitleText"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
<ScrollView
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize"
app:layout_constraintTop_toBottomOf="@id/toolbar"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent">
<!-- Content of fragment_main.xml -->
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingStart="50dp"
android:paddingEnd="50dp"
tools:context=".MainFragment">
<ImageButton
android:id="@+id/overlay_button"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@null"
android:contentDescription="@string/start_speedometer"
android:scaleType="fitCenter"
android:src="@drawable/btn_circle_green"
app:layout_constraintDimensionRatio="1:1"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
<TextView
android:id="@+id/overlay_button_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="false"
android:text="@string/start_speedometer"
android:textColor="@color/white"
android:textSize="40sp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
<com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="false"
app:menu="@menu/nav_drawer_view"
app:headerLayout="@layout/nav_drawer_header"
app:itemIconTint="@drawable/nav_drawer_item_icon_color"
app:itemTextColor="@drawable/nav_drawer_item_text_color" />
</androidx.drawerlayout.widget.DrawerLayout>
Я ищу решение, в котором мне нужно только внести изменения в fragment_main.xml
(то есть все внутри ScollView
).Решение должно включать только XML.
То, что я пробовал
Я пробовал играть с app:layout_constraintDimensionRatio
(W,1:1
, H,1:1
), app:layout_constrainedHeight
, app:layout_constraintHeight_max
, layout_constraintHeight_min
, многие другие ограничения и даже пытались вложить содержимое fragment_main.xml
в другие макеты, перемещены с ConstraintLayout
на RelativeLayout
, LinearLayout
и FrameLayout
, но ни одно из них не дает мне желаемого результата иConstraintLayout
- самое близкое.
Возможное решение
Единственное решение, которое до сих пор работало, - это использование app:layout_constraintWidth_default="percent"
и app:layout_constraintWidth_percent="0.5"
, в результате чего желаемый вид активности_основной.xml в альбомной ориентации
Хотя это может выглядеть прекрасно на телефоне формата 16: 9, это может привести к тем же проблемам, что и на телефонах с другим соотношением сторон.Поэтому я ищу более общий подход.
Дополнительные сведения
Это содержимое рисованного элемента btn_circle_green.xml
, который я использую для кнопки:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/ic_circle_green_pressed" />
<item android:state_focused="true" android:drawable="@drawable/ic_circle_green_focused" />
<item android:state_selected="true" android:drawable="@drawable/ic_circle_green_focused" />
<item android:drawable="@drawable/ic_circle_green_default" />
</selector>
Каждый ic_circle_green_*
является векторным активом, подобным этому, с разными цветами:
<vector
android:viewportWidth="300"
android:viewportHeight="300"
android:height="120dp"
android:width="120dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="@color/green"
android:pathData="M150,150m-140,0a140,140 0,1 1,280 0a140,140 0,1 1,-280 0"
android:strokeWidth="5"
android:strokeColor="@color/green_light"/>
</vector>
Большое спасибо заранее!