gpt4 book ai didi

c# - 有没有办法以编程方式在 android 中创建布局的副本?

转载 作者:太空宇宙 更新时间:2023-11-03 22:55:47 25 4
gpt4 key购买 nike

主要目标是使用预制布局创建可编辑的单独模块,然后以编程方式将它们添加到根布局。澄清一下,several modules stuck together would look like this.我想动态创建每个由名称、日期和字母组成的可点击 block 。每个 block 的.axml代码如下:

        <RelativeLayout
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/borderLayout"
android:background="@drawable/line"
android:paddingBottom="1dp"
android:paddingTop="1dp">
<RelativeLayout
android:id="@+id/relativeLayout1"
android:padding="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:background="#ff2f2f2f">
<TextView
android:text="C"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView1"
android:layout_alignParentLeft="true"
android:textSize="30dp" />
<TextView
android:text="Washington"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/textView1"
android:id="@+id/textView2"
android:layout_alignParentRight="true"
android:gravity="right" />
<TextView
android:text="6-8-17"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textView2"
android:id="@+id/textView3"
android:gravity="right"
android:layout_alignParentRight="true" />
</RelativeLayout>
</RelativeLayout>

我遇到的主要问题是以编程方式格式化 View 的方式与我在 .axml 文件中格式化它们的方式相同。

最佳答案

假设您在主 axml 中有一个方向为 verticalLinearLayout,您希望将多个 View 附加到该 LinearLayout

获取对该“父级”LinearLayout 的引用:

var linearLayoutParent = FindViewById<LinearLayout>(Resource.Id.linearLayout1);

然后在某个循环中,使用 LayoutInflater.Inflate 来膨胀你的重复布局,使用返回的 View 和 FindViewById 在每个 View 上您需要更新的元素,然后将该 View 添加到具有递增索引的父 View :

index++;
var view = LayoutInflater.Inflate(Resource.Layout.RepeatingLayout, linearLayoutParent, false);
var letter = view.FindViewById<TextView>(Resource.Id.textView1);
letter.Text = index.ToString();
// FindViewById for textView2, textView3 and assign the text on each....
linearLayoutParent.AddView(view, index);

enter image description here

注意:如果你有很多这样的重复元素并且你将不得不滚动它们(离开屏幕),看看使用 RecyclerView 代替,它会让你省去很多令人头疼的术语内存管理、滚动性能等...;-)

关于c# - 有没有办法以编程方式在 android 中创建布局的副本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45420870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com