Jetpack Compose 和 Android View 之间的对应关系

411 阅读6分钟

Compose

Jetpack Compose 与 Android View 对应关系的表格整理:

基础组件

ComposeAndroid View
TextTextView
TextFieldEditText
ButtonButton
ImageImageView
IconImageView
BoxFrameLayout
RowLinearLayout (horizontal)
ColumnLinearLayout (vertical)
LazyColumnRecyclerView (vertical)
LazyRowRecyclerView (horizontal)
LazyVerticalGridGridView/RecyclerView+GridLayoutManager
SurfaceCardView

布局组件

ComposeAndroid View
ScaffoldActivity/Fragment 基础布局
ConstraintLayoutConstraintLayout
BoxWithConstraintsConstraintLayout
FlowRow/FlowColumnFlexboxLayout
SpacerSpace/View (用作间距)

导航组件

ComposeAndroid View
TopAppBarToolbar/ActionBar
NavigationBarBottomNavigationView
NavigationRailNavigationView
TabRowTabLayout

交互组件

ComposeAndroid View
CheckboxCheckBox
SwitchSwitch
SliderSeekBar
RadioButtonRadioButton
DropdownMenuPopupMenu/Spinner
AlertDialogAlertDialog
ModalBottomSheetBottomSheetDialog

列表相关

ComposeAndroid View
PullToRefreshBoxSwipeRefreshLayout
HorizontalPager/VerticalPagerViewPager/ViewPager2
LazyVerticalStaggeredGridRecyclerView + StaggeredGridLayoutManager

输入组件

ComposeAndroid View
OutlinedTextFieldTextInputLayout + EditText
BasicTextFieldEditText
TextButtonButton (文本样式)
OutlinedButtonButton (边框样式)
FloatingActionButtonFloatingActionButton

高级列表组件

ComposeAndroid View
LazyVerticalStaggeredGridRecyclerView + StaggeredGridLayoutManager
LazyHorizontalStaggeredGridRecyclerView + StaggeredGridLayoutManager (horizontal)
LazyColumn + sticky headerRecyclerView + ItemDecoration (吸顶效果)
LazyVerticalGridRecyclerView + GridLayoutManager

手势和交互

ComposeAndroid View
Modifier.draggableOnTouchListener + GestureDetector
Modifier.swipeableItemTouchHelper
Modifier.scrollableScrollView/NestedScrollView
Modifier.zoomableScaleGestureDetector
Modifier.combinedClickableGestureDetector

动画组件

ComposeAndroid View
AnimatedVisibilityViewAnimator/Animation
AnimatedContentViewFlipper + Animation
CrossfadeTransitionManager
animateContentSizeValueAnimator + layout changes
SharedElementTransitionActivityOptions.makeSceneTransitionAnimation

自定义视图

ComposeAndroid View
CanvasCustomView (onDraw)
BasicTextFieldAppCompatEditText
DrawScopeCanvas
LayoutViewGroup

约束布局高级特性

ComposeAndroid View
ConstraintLayout (Barrier)Barrier
ConstraintLayout (Guideline)Guideline
ConstraintLayout (Chain)Chain
MotionLayoutMotionLayout

状态管理

ComposeAndroid View
rememberViewModel/SavedInstanceState
rememberSaveableonSaveInstanceState
derivedStateOfLiveData/StateFlow transformations

嵌套滚动

ComposeAndroid View
nestedScroll modifierNestedScrollView
NestedScrollConnectionNestedScrollingChild/Parent
rememberNestedScrollInteropConnectionCoordinatorLayout behaviors

Material Design 组件

ComposeAndroid View
ModalBottomSheetBottomSheetDialogFragment
BottomSheetScaffoldBottomSheetBehavior
SnackbarHostSnackbar
BadgedBoxBadgeDrawable
NavigationDrawerDrawerLayout

自适应导航组件

Compose使用场景
NavigationSuiteScaffold自适应导航脚手架,根据屏幕尺寸自动选择合适的导航方式
NavigationBar底部导航栏,适用于手机
NavigationRail侧边导航栏,适用于平板/折叠屏
ModalNavigationDrawer模态抽屉式导航,可滑动展开/关闭
PermanentNavigationDrawer永久显示的抽屉式导航,适用于大屏设备

自适应窗格布局

Compose使用场景
NavigableListDetailPaneScaffold列表-详情双窗格布局,适用于主从布局
NavigableSupportingPaneScaffold主要内容-辅助内容双窗格布局
TwoPane基础的双窗格布局组件
AdaptivePane自适应窗格,根据屏幕尺寸调整布局

Modifier

Modifier 是 Jetpack Compose 中最重要的概念之一,它允许您装饰或增强可组合项的外观和行为。以下是 Modifier 的详细介绍:

1. Modifier 基础概念

  • 链式调用:Modifier 通过链式调用组合多个修饰符
  • 顺序敏感:修饰符的应用顺序会影响最终效果(从上到下,从外到内)
  • 不可变:每次修改都会返回新的 Modifier 实例

2. 布局修饰符 (Layout Modifiers)

修饰符作用对应 View 系统概念
size(width: Dp, height: Dp)设置固定尺寸layout_width/layout_height
width(width: Dp)设置固定宽度layout_width
height(height: Dp)设置固定高度layout_height
fillMaxSize(fraction: Float = 1f)填充最大可用空间match_parent
fillMaxWidth(fraction: Float = 1f)填充最大宽度match_parent (横向)
fillMaxHeight(fraction: Float = 1f)填充最大高度match_parent (纵向)
wrapContentSize(align: Alignment = Alignment.Center)包裹内容wrap_content
requiredSize(size: Dp)强制尺寸(忽略父项约束)-
sizeIn(minWidth: Dp, minHeight: Dp, maxWidth: Dp, maxHeight: Dp)设置尺寸范围minWidth/maxWidth 等

3. 内边距和边距修饰符

修饰符作用对应 View 系统概念
padding(all: Dp)统一设置内边距padding
padding(horizontal: Dp, vertical: Dp)分别设置水平和垂直内边距padding
padding(start: Dp, top: Dp, end: Dp, bottom: Dp)分别设置各边内边距padding
offset(x: Dp, y: Dp)偏移组件位置translationX/translationY
absoluteOffset(x: Dp, y: Dp)绝对偏移(不考虑布局方向)-

4. 图形修饰符 (Drawing Modifiers)

修饰符作用对应 View 系统概念
background(color: Color, shape: Shape = RectangleShape)设置背景setBackgroundColor
clip(shape: Shape)按形状裁剪setClipToOutline
alpha(alpha: Float)设置透明度setAlpha
rotate(degrees: Float)旋转setRotation
scale(scaleX: Float, scaleY: Float)缩放setScaleX/setScaleY
graphicsLayer { ... }高级图形变换View.setCameraDistance 等
shadow(elevation: Dp, shape: Shape = RectangleShape, clip: Boolean = elevation > 0.dp)添加阴影elevation

5. 交互修饰符 (Interaction Modifiers)

修饰符作用对应 View 系统概念
clickable(onClick: () -> Unit)点击事件setOnClickListener
combinedClickable(onClick: () -> Unit, onDoubleClick: () -> Unit, onLongClick: () -> Unit)组合点击事件GestureDetector
hoverable(state: MutableInteractionSource)悬停状态setOnHoverListener
focusable()获取焦点能力setFocusable
focusRequester(focusRequester: FocusRequester)焦点请求器requestFocus
scrollable(state: ScrollableState, orientation: Orientation)可滚动ScrollView
draggable(state: DraggableState, orientation: Orientation)可拖动OnTouchListener
swipeable(state: SwipeableState, anchors: Map<Float, T>, orientation: Orientation)可滑动ViewDragHelper

6. align 修饰符详解

align 是用于在 Box 布局中对子组件进行对齐定位的关键修饰符。

基本用法

Box(modifier = Modifier.fillMaxSize()) {
    Text(
        text = "居中文本",
        modifier = Modifier.align(Alignment.Center) // 居中
    )
}

对齐选项

对齐方式描述对应 Android View 概念
Alignment.TopStart左上角`Gravity.STARTGravity.TOP`
Alignment.TopCenter顶部居中`Gravity.CENTER_HORIZONTALGravity.TOP`
Alignment.TopEnd右上角`Gravity.ENDGravity.TOP`
Alignment.CenterStart左侧居中`Gravity.STARTGravity.CENTER_VERTICAL`
Alignment.Center正中心Gravity.CENTER
Alignment.CenterEnd右侧居中`Gravity.ENDGravity.CENTER_VERTICAL`
Alignment.BottomStart左下角`Gravity.STARTGravity.BOTTOM`
Alignment.BottomCenter底部居中`Gravity.CENTER_HORIZONTALGravity.BOTTOM`
Alignment.BottomEnd右下角`Gravity.ENDGravity.BOTTOM`

高级用法

  1. 自定义对齐比例(非标准位置):

    // 将子组件放置在横向30%、纵向70%的位置
    Modifier.align(Alignment(0.3f, 0.7f))
    
  2. 与 Box 的其他特性结合

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.LightGray)
    ) {
        Box(
            modifier = Modifier
                .size(100.dp)
                .background(Color.Red)
                .align(Alignment.BottomEnd)
                .padding(16.dp) // 会在对齐后添加内边距
        )
    }
    

与其他修饰符的区别

修饰符作用范围典型使用场景
align仅作用于 Box 的直接子项在容器内精确定位单个元素
Arrangement作用于 Row/Column 的子项整体排列控制行/列中子项的分布方式
padding影响自身布局增加组件内边距
offset视觉偏移(不改变布局占用空间)微调显示位置

注意事项

  1. 仅限 Box 子项align 只能在 Box 布局内使用,在 Row/Column 中无效
  2. 与 weight 冲突:不能同时使用 align 和 Modifier.weight
  3. 性能影响:比 offset 更符合布局系统,不会导致过度绘制

对比传统 View 的实现

<!-- Android View 方式 -->
<FrameLayout android:layout_width="match_parent" 
             android:layout_height="match_parent">
    <TextView
        android:layout_gravity="bottom|end"
        android:text="右下角文本"/>
</FrameLayout>

align 修饰符提供了比传统 layout_gravity 更灵活的对齐控制,特别是支持自定义比例对齐,这是 Compose 布局系统的优势之一。

7. 高级修饰符

修饰符作用对应 View 系统概念
onGloballyPositioned { coordinates -> ... }获取全局位置ViewTreeObserver.OnGlobalLayoutListener
onSizeChanged { size -> ... }尺寸变化监听OnLayoutChangeListener
pointerInput(key: Any?, block: suspend PointerInputScope.() -> Unit)自定义手势处理GestureDetector
semantics { ... }设置语义属性contentDescription
zIndex(zIndex: Float)设置Z轴顺序elevation
drawWithContent { drawContent() }自定义绘制View.onDraw
drawWithCache { ... }带缓存的绘制View.onDraw 带缓存
layout { measurable, constraints -> ... }自定义布局View.onMeasure/onLayout

8. 修饰符组合技巧

  1. 常用组合模式

    Modifier
        .padding(16.dp)
        .fillMaxWidth()
        .clickable { /* 点击处理 */ }
        .background(Color.Blue, RoundedCornerShape(8.dp))
    
  2. 创建自定义修饰符扩展

    fun Modifier.cardElevation(): Modifier = this
        .shadow(8.dp, RoundedCornerShape(8.dp))
        .background(Color.White, RoundedCornerShape(8.dp))
        .padding(8.dp)
    
  3. 条件修饰符

    Modifier
        .padding(16.dp)
        .then(if (isEnabled) Modifier.clickable { onClick() } else Modifier)
    

9. 性能考虑

  1. 避免在动画中使用高开销修饰符(如 graphicsLayer
  2. 重用 Modifier 实例:对于静态修饰符,可以创建常量
  3. 谨慎使用 drawWithContent 和 layout:这些是重量级操作
  4. 使用 drawWithCache 替代重复绘制:当内容不变时

10. 最佳实践

  1. 保持修饰符链清晰:按布局→形状→交互→图形的顺序组织
  2. 提取常用修饰符组合:提高代码复用性
  3. 注意修饰符顺序padding 在 background 前或后效果不同
  4. 利用 Modifier.composed:创建可重用、有状态的修饰符

11. 示例对比

Android View 方式

View view = new View(context);
view.setLayoutParams(new LayoutParams(MATCH_PARENT, WRAP_CONTENT));
view.setPadding(16, 16, 16, 16);
view.setBackground(new RoundRectDrawable(radius, color));
view.setOnClickListener(v -> { /* ... */ });

Compose 方式

Box(
    modifier = Modifier
        .fillMaxWidth()
        .wrapContentHeight()
        .padding(16.dp)
        .background(Color.Blue, RoundedCornerShape(8.dp))
        .clickable { /* ... */ }
) { /* content */ }

Modifier 提供了比传统 View 系统更灵活、更声明式的方式来定义 UI 组件的外观和行为,是 Compose 强大功能的核心所在。