gpt4 book ai didi

android - 膨胀与 findViewById

转载 作者:IT老高 更新时间:2023-10-28 23:34:02 26 4
gpt4 key购买 nike

假设我有一个简单的布局 xml,如下所示:

button.xml:

<Button
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

以下调用有什么不同吗?我应该使用哪一个?

button = (Button) getLayoutInflater().inflate(R.layout.button, null);

View v = getLayoutInflater().inflate(R.layout.button, null);
button = (Button) v.findViewById(R.id.button01);

最佳答案

这会创建一个具有给定布局的新 View ,其中“R.layout.button”由 xml 文件“button.xml”的名称生成。每次调用 .inflate(...) 都会得到一个新实例。

View v = getLayoutInflater().inflate(R.layout.button, null);

--

虽然在 R.id.button01 由 id 名称“android:id="@+id/button01"' 生成的布局中找到现有 View 。每次调用 .findViewById(R.id.button01) 时,您都会得到相同的实例,因为 View ​​'v' 将是相同的。

button = (Button) v.findViewById(R.id.button01);

关于android - 膨胀与 findViewById,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2542897/

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