【问题标题】:Change layout in 'Include' programmatically using Kotlin使用 Kotlin 以编程方式更改“包含”中的布局
【发布时间】:2020-01-22 03:45:10
【问题描述】:

我正在编写一个简单的游戏,我希望主屏幕有 3 种布局可供选择,适用于 2 手、右手或左手。

我有一个include 用于控件。但是,我正在努力让layout 以编程方式进行更改。从昨晚开始一直在寻找,但找不到方法,这可能吗?

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".GamePlay">
 <include
        android:layout_width="match_parent"
        android:layout_height="88dp"
        layout="@layout/hand_two" <!-- this is what needs to change depending on settings -->
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:id="@+id/handLayout"/>
</androidx.constraintlayout.widget.ConstraintLayout>

【问题讨论】:

标签: android android-studio kotlin


【解决方案1】:

来自animusmindanswer: 使用 ViewStub 而不是包含:

<ViewStub
    android:id="@+id/layout_stub"
    android:inflatedId="@+id/message_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="0.75" />

然后在代码中,获取对存根的引用,设置其布局资源,并对其进行扩充:

ViewStub stub = (ViewStub) findViewById(R.id.layout_stub);
stub.setLayoutResource(R.layout.whatever_layout_you_want);
View inflated = stub.inflate();

kcoppock

收集的答案

【讨论】:

  • 不理想必须使用存根,因为我在布局中看不到它,但已经走了这条路。以上是Java,但我不知道。我想我已经成功了,谢谢
【解决方案2】:

如果您希望以编程方式按需加载多个视图,ViewStub 就是其中一种解决方案

请点赞链接viewStub for multiple view

【讨论】:

    猜你喜欢
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多