View 体系
View 体系 · androidx.core
AsyncLayoutInflater:后台线程加载布局Core 1.20.0-alpha01
在非 UI 线程 inflate XML,减少首次进入页面的卡顿。
最后更新 2026-08-01
复制即用
import androidx.asynclayoutinflater.view.AsyncLayoutInflater;
new AsyncLayoutInflater(context).inflate(
R.layout.item_detail,
parent,
(view, resid, parentView) -> {
// 主线程回调,可安全更新 UI
container.addView(view);
((TextView) view.findViewById(R.id.title)).setText("标题");
}
);为什么用
inflate在后台线程解析 XML(开销在LayoutInflater的inflate)。- 完成后在主线程回调——回调中才能安全操作 View。
- 适用:进入页面时预加载复杂布局(如详情页底部内容)。
与普通 inflate 对比
| 方式 | 线程 | 适用 |
|---|---|---|
LayoutInflater.inflate | 主线程(同步) | 简单布局 |
AsyncLayoutInflater.inflate | 后台(异步回调) | 复杂布局首屏优化 |
| RecyclerView + ViewHolder | 复用 | 高频列表项 |
关键约束
- 回调在主线程:布局创建后的 View 操作放回调里。
- 必须传 parent:
LayoutParams来源,不传可能丢布局参数。 - 监听器回调和取消:
inflate完成前页面销毁,回调仍会执行——需要检查 View 是否还 attached。
new AsyncLayoutInflater(context).inflate(
R.layout.item_detail, parent,
(view, resid, parentView) -> {
if (container.isAttachedToWindow()) { // 防页面已销毁
container.addView(view);
}
}
);常见陷阱
- 简单布局也用:线程切换开销可能大于收益。
- 高频列表项用:应走 RecyclerView 复用,不是异步 inflate。
- 回调里操作已销毁 View:页面离开后回调执行 → 崩溃,检查 attached。
- 忘 parent:LayoutParams 丢失,布局异常。
复制即用
public class DetailFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_detail, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ViewGroup content = view.findViewById(R.id.detail_content);
// 复杂子布局异步加载
new AsyncLayoutInflater(requireContext()).inflate(
R.layout.expensive_widget,
content,
(loadedView, resid, parentView) -> {
if (isAdded() && content.isAttachedToWindow()) {
content.addView(loadedView);
}
}
);
}
}要点
- 后台 inflate + 主线程回调;适合复杂布局首屏优化。
- 简单布局/高频列表项别用。
- 回调要检查 View 是否 still attached。
- 传 parent 保证 LayoutParams 正确。