Android View 对应的 Compose

From

原文来自 https://juejin.cn/post/7490989659033714722 如有侵权,请联系

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

Compose

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

基础组件

Compose Android View
Text TextView
TextField EditText
Button Button
Image ImageView
Icon ImageView
Box FrameLayout
Row LinearLayout (horizontal)
Column LinearLayout (vertical)
LazyColumn RecyclerView (vertical)
LazyRow RecyclerView (horizontal)
LazyVerticalGrid GridView/RecyclerView+GridLayoutManager
Surface CardView

布局组件

Compose Android View
Scaffold Activity/Fragment 基础布局
ConstraintLayout ConstraintLayout
BoxWithConstraints ConstraintLayout
FlowRow/FlowColumn FlexboxLayout
Spacer Space/View (用作间距)

导航组件

Compose Android View
TopAppBar Toolbar/ActionBar
NavigationBar BottomNavigationView
NavigationRail NavigationView
TabRow TabLayout

交互组件

Compose Android View
Checkbox CheckBox
Switch Switch
Slider SeekBar
RadioButton RadioButton
DropdownMenu PopupMenu/Spinner
AlertDialog AlertDialog
ModalBottomSheet BottomSheetDialog

列表相关

Compose Android View
PullToRefreshBox SwipeRefreshLayout
HorizontalPager/VerticalPager ViewPager/ViewPager2
LazyVerticalStaggeredGrid RecyclerView + StaggeredGridLayoutManager

输入组件

Compose Android View
OutlinedTextField TextInputLayout + EditText
BasicTextField EditText
TextButton Button (文本样式)
OutlinedButton Button (边框样式)
FloatingActionButton FloatingActionButton

高级列表组件

Compose Android View
LazyVerticalStaggeredGrid RecyclerView + StaggeredGridLayoutManager
LazyHorizontalStaggeredGrid RecyclerView + StaggeredGridLayoutManager (horizontal)
LazyColumn + sticky header RecyclerView + ItemDecoration (吸顶效果)
LazyVerticalGrid RecyclerView + GridLayoutManager

手势和交互

Compose Android View
Modifier.draggable OnTouchListener + GestureDetector
Modifier.swipeable ItemTouchHelper
Modifier.scrollable ScrollView/NestedScrollView
Modifier.zoomable ScaleGestureDetector
Modifier.combinedClickable GestureDetector

动画组件

Compose Android View
AnimatedVisibility ViewAnimator/Animation
AnimatedContent ViewFlipper + Animation
Crossfade TransitionManager
animateContentSize ValueAnimator + layout changes
SharedElementTransition ActivityOptions.makeSceneTransitionAnimation

自定义视图

Compose Android View
Canvas CustomView (onDraw)
BasicTextField AppCompatEditText
DrawScope Canvas
Layout ViewGroup

约束布局高级特性

Compose Android View
ConstraintLayout (Barrier) Barrier
ConstraintLayout (Guideline) Guideline
ConstraintLayout (Chain) Chain
MotionLayout MotionLayout

状态管理

Compose Android View
remember ViewModel/SavedInstanceState
rememberSaveable onSaveInstanceState
derivedStateOf LiveData/StateFlow transformations

嵌套滚动

Compose Android View
nestedScroll modifier NestedScrollView
NestedScrollConnection NestedScrollingChild/Parent
rememberNestedScrollInteropConnection CoordinatorLayout behaviors

Material Design 组件

Compose Android View
ModalBottomSheet BottomSheetDialogFragment
BottomSheetScaffold BottomSheetBehavior
SnackbarHost Snackbar
BadgedBox BadgeDrawable
NavigationDrawer DrawerLayout

自适应导航组件

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.START | Gravity.TOP` |
| Alignment.TopCenter | 顶部居中 | `Gravity.CENTER_HORIZONTAL | Gravity.TOP` |
| Alignment.TopEnd | 右上角 | `Gravity.END | Gravity.TOP` |
| Alignment.CenterStart | 左侧居中 | `Gravity.START | Gravity.CENTER_VERTICAL` |
| Alignment.Center | 正中心 | Gravity.CENTER |
| Alignment.CenterEnd | 右侧居中 | `Gravity.END | Gravity.CENTER_VERTICAL` |
| Alignment.BottomStart | 左下角 | `Gravity.START | Gravity.BOTTOM` |
| Alignment.BottomCenter | 底部居中 | `Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM` |
| Alignment.BottomEnd | 右下角 | `Gravity.END | Gravity.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 强大功能的核心所在。

posted @ 2025-06-11 15:34  一个小笨蛋  阅读(123)  评论(0)    收藏  举报