【发布时间】:2020-05-25 15:31:17
【问题描述】:
我想以编程方式为我的主布局设置边距。我使用布局参数作为以下代码。
val parMain = mainLayout?.layoutParams as ConstraintLayout.LayoutParams
但我有一些错误,例如
android.view.ViewGroup$LayoutParams 不能转换为 androidx.constraintlayout.widget.ConstraintLayout$LayoutParams
如果我按照 Android 的要求更改代码:
val parMain = mainLayout?.layoutParams as ViewGroup.LayoutParams
我的 layoutParams 中没有设置边距功能。
这是我的 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"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/detail_feed_scrool_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/transparent"
tools:context=".DetailActivity">
<View
android:id="@+id/shadow_view"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:background="#99000000"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.viewpager.widget.ViewPager
android:id="@+id/detail_feed_view_pager_activity"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</androidx.viewpager.widget.ViewPager>
<FrameLayout
android:id="@+id/detail_fragment_frame_layout"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@android:color/white"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
在我的情况下如何设置边距?
【问题讨论】:
-
mainLayout 是哪一个?? detail_feed_scool_view??
-
是的。 var mainLayout = findViewById(R.id.detail_feed_scrool_view)
-
我认为您对为什么会感兴趣,不是吗?所以我提供了详细的答案
-
我尝试使用 FrameLayout.LayoutParams。只是错误消息改变如下: android.view.ViewGroup$LayoutParams cannot be cast to android.widget.FrameLayout$LayoutParams
-
我在回答中解释了
LayoutParams的概念,请立即查看答案,您将能够解决您的问题
标签: java android kotlin layoutparams layoutmargins