Skip to content

xesam/Android-Size

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Android-Size

简介

Android-Size 是一个 Android 尺寸转换工具库,提供了一套完整的 API 用于处理 Android 应用中的各种尺寸单位(dp、sp、px)之间的转换和计算。该库旨在简化 Android 开发中的尺寸处理,提高代码可读性和维护性。

特性

  • 支持 dp(密度无关像素)、sp(缩放无关像素)和 px(像素)之间的无缝转换
  • 提供面向对象的尺寸处理方式,使代码更加清晰和易于维护
  • 支持尺寸的加减乘除等基本运算
  • 支持从资源文件中获取尺寸
  • 最低支持 Android API 19 (Android 4.4 KitKat)

安装

在应用模块的 build.gradle 文件中添加依赖:

dependencies {
    implementation 'io.github.xesam:android-size:0.0.1'
}

使用方法

基本使用

// 创建尺寸对象
Dp dpValue = new Dp(16);
Sp spValue = new Sp(14);
Px pxValue = new Px(48);

// 单位转换
float pxFromDp = dpValue.toPx(context);
float dpFromPx = pxValue.toDp(context);
float spFromDp = dpValue.toSp(context);

尺寸计算

// 尺寸加法
UnitDimen sum = new Dp(10).plus(new Dp(5));  // 结果为 15dp

// 尺寸减法
UnitDimen difference = new Dp(20).minus(new Dp(8));  // 结果为 12dp

// 尺寸乘法
UnitDimen product = new Dp(10).times(2);  // 结果为 20dp

// 尺寸除法
UnitDimen quotient = new Dp(30).div(3);  // 结果为 10dp

从资源获取尺寸

// 从资源文件获取尺寸
UnitDimen resourceDimen = UnitDimen.fromRes(context, R.dimen.my_dimension);

尺寸对象

库提供了以下尺寸类型:

  • Dp - 密度无关像素
  • Sp - 缩放无关像素(适用于文本大小)
  • Px - 设备像素
  • DpSizeSpSizePxSize - 二维尺寸对象,包含宽度和高度

示例

// 创建一个按钮并设置其尺寸
Button button = new Button(context);
Dp buttonWidth = new Dp(120);
Dp buttonHeight = new Dp(48);

// 转换为像素并应用
button.setLayoutParams(new ViewGroup.LayoutParams(
    (int) buttonWidth.toPx(context),
    (int) buttonHeight.toPx(context)
));

// 设置文本大小
Sp textSize = new Sp(16);
button.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize.toPx(context));

许可证

Copyright (c) 2024 xesam

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages