gpt4 book ai didi

java - 动态添加与基础布局相同的相对布局

转载 作者:行者123 更新时间:2023-11-29 22:58:58 25 4
gpt4 key购买 nike

如何根据 xml 布局动态生成 RelativeLayout(下面发布)?相关布局被放置在线性布局中,该布局是 ScrollView 的 subview 。

<RelativeLayout
android:id="@+id/post_0"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp">

<TextView
android:id="@+id/op_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="8dp"
android:text="Username" />

<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_below="@+id/op_username"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginStart="31dp"
android:layout_marginLeft="31dp"
android:layout_marginTop="15dp"
app:srcCompat="@android:drawable/btn_star_big_on"
tools:srcCompat="@android:drawable/btn_star_big_on" />
</RelativeLayout>

最佳答案

假设您的数据库中有所有图像及其 TextView 的文本,然后创建一个 RecyclerView (如果项目数量相对较多)或简单的 ListView ,然后创建一个 CustomAdapter 类以将您的 RelativeLayout 添加到您的主 ListView/ScrollView/RecyclerView .

要完全实现这一点,您首先需要有一个 Item 类,它可以在对象中存储用户的用户名和图像(请注意,您需要将图像 URI 作为字符串传递)。

public class Items {

private final int id;
private final String image;

public Items(int id,String image){
this.name=name;
this.image=image;
}
//Include all the Getters and Setters here
}

然后假设您已将所有元素放入 ArrayList<Items> 中, 那么你需要实现一个 Adapter 类,称为 CustomAdaper ,它扩展了 ArrayAdapter 并且需要为 getView 编写一个函数获取特定 View 以填写您的 ScrollView/RecyclerView/ListView

我找到了一个链接来帮助您实现 CustomAdapter here .

最后在 MainActivity 中,您必须添加几行,

final ListView listView = (ListView) findViewById(R.id.list_view);    //name of list view file
final ArrayList<Items> arrayList = dbHelper.retrieveFromDB(); // Name of the Database class and the function to retrieve all the elements into an ArrayList in that class
CustomAdapter adapter = new CustomAdapter(this /* The current Context */, R.layout.list_item, arrayList); // Create an object of custom adapter initialize it with the desired data (in this case the arrayList) and the layout required ( layout mentioned in the question)
listView.setAdapter(adapter);

关于java - 动态添加与基础布局相同的相对布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57128138/

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