java - CardView 没有使用 LayoutInflater 正确充气
问题描述
我想以编程方式添加 CardView。
这是我的主要活动 XML 布局 (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/linearLayout1"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical">
</LinearLayout>
这是我的 CardViewTemplate (card_view_template.xml)
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/cardViewTemplate"
android:layout_width="160dp"
android:layout_height="190dp"
android:layout_margin="10dp"
android:clickable="true"
android:foreground="?android:selectableItemBackground">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="This is a Card" />
</androidx.cardview.widget.CardView>
这是我的 Java 代码 (MainActivity.java)
LayoutInflater inflater = getLayoutInflater();
ViewGroup parent = findViewById(R.id.linearLayout1);
inflater.inflate(R.layout.card_view_template, parent);
直到这里一切正常。
现在我想在我的activity_main.xml中的某个位置添加卡片,因为我正在使用多个 CardViews,我想在某个位置添加卡片。因此,我尝试了以下代码,而不是上面的代码:
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.card_view_template, null);
ViewGroup parent = findViewById(R.id.linearLayout1);
parent.addView(view, 0);
解决方案
当动态添加视图时,我们不应该View
用 nullViewGroup
父级膨胀。
在此View view = inflater.inflate(R.layout.card_view_template, null);
此处将父级指定为空,这导致了问题。
指定将附加到的View
父级,并且仅将附加到父级设置为false
。这样将指定但不附加父项。
因此首先声明父(根),然后创建View
并指定父(根)并将附加设置为父(根)false
这是正确的说法
View view = inflater.inflate(R.layout.card_view_template, parent, false);
因此完整的代码将是:
LayoutInflater inflater = getLayoutInflater();
ViewGroup parent = findViewById(R.id.linearLayout1);
View view = inflater.inflate(R.layout.card_view_template, parent, false);
parent.addView(view, 0);
推荐阅读
- google-apps-script - 您无法切换到 Apps 脚本创建的 Cloud Platform 项目 - 将 Apps 脚本文件与 Cloud 项目相关联
- python - 如何将 cross_validation 与 curve_fit 一起使用?
- c# - 在不同的运行期间解密加密的字符串
- javascript - 在哪里可以找到添加到 MicroTask Queue 的项目的完整列表?
- git - git 存储库中的 Composer 包冲突;如何在推送到远程时取消跟踪文件但避免删除文件
- python - 查找分类数据的十分位数?
- ruby-on-rails - 您可以使用 Webpacker 在 Rails 6 应用程序中直接使用 Web3.js 吗?
- crystal-reports - Crystal Reports 中的坐标系
- c# - 如何创建具有私有类型参数和返回类型的快速调用委托,加速 DynamicInvoke
- php - 我在一些 Wordpress 帖子中有 404 答案