[英]Change layout in 'Include' programmatically using Kotlin
我正在编写一个简单的游戏,我希望主屏幕可以选择 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>
从animusmind的回答:使用 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收集的答案
如果您有多个视图希望以编程方式按需加载它们,ViewStub 是解决方案之一
请访问类似链接viewStub 以获得多个视图
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.