您的位置:首页 > 移动开发 > Android开发

Android开发中算法积累小结

2017-06-21 22:21 387 查看
1.讲一个List集合中的所有元素分组,

比如26个字母,每组最多6个的分组算法:

// 现将26个字母添加到集合中
List<String> list = new LinkedList<>();
for (char i = 'A'; i <= 'Z'; i++) {
list.add(String.valueOf(i));
}
// 字母总的个数
int totalSum = list.size();
// 分组后每组最大个数
int everyPageMaxSum = 6;
// 算出要分成几组 totalSum要弄成浮点,那样才会取到最大整数
int group = (int) Math.ceil(totalSum * 1.0f / everyPageMaxSum);

int start = 0;// 开始索引
// 每页的最大个数和总数比较
int end = everyPageMaxSum > totalSum ? totalSum : everyPageMaxSum;

for (int i = 0; i < group; i++) {
start = i * everyPageMaxSum;// 开始
end = everyPageMaxSum + i * everyPageMaxSum;// 结束
if (end >= totalSum) {// 超过了就取到元素总个数
end = totalSum;
}

List<String> arr = list.subList(start, end);// 按组截取
System.out.println(arr.toString());
System.out.println("------------------");
}

}


打印内容如下:

[A, B, C, D, E, F]
------------------
[G, H, I, J, K, L]
------------------
[M, N, O, P, Q, R]
------------------
[S, T, U, V, W, X]
------------------
[Y, Z]
------------------


2.在开发中用到适配器,有时并不是将所有数据都放到一个集合中,而是分到几个集合中,实际上还是由一个适配器展示,那么如何根据适配器中数据的位置来从集合中获取数据元素;

算法原理:



代码演示如下:

static List<String> aList = new ArrayList<>();// a集合
static List<String> bList = new ArrayList<>();// b集合
static List<String> cList = new ArrayList<>();// c集合
static List<List<String>> All = new ArrayList<>();// 全部集合
static int count;// 所有集合中的元素总数

public static void main(String[] args) {
init();
System.out.println(getValueFromPos(3));
System.out.println(getValueFromPos(4));
System.out.println(getValueFromPos(6));
}

private static void init() {
// 第一个集合中添加4个元素
for (int i = 1; i <= 4; i++) {
aList.add("A-List-------" + i);
}
// 第二个集合中添加2个元素
for (int i = 1; i <= 2; i++) {
bList.add("B-List-------" + i);
}
// 第三个集合中添加1个元素
for (int i = 1; i <= 1; i++) {
cList.add("C-List-------" + i);
}

// 三个集合全部添加到 All中
All.add(aList);
All.add(bList);
All.add(cList);

// 三个集合中所有子元素的个数
count = aList.size() + aList.size() + cList.size();
}

// 根据位置position从All中取出对应子元素
public static String getValueFromPos(int position) {
// 超出元素个数 返回null
if (position > count)
return null;
// 遍历
for (List<String> list : All) {
// position索引位于某个集合的范围 就从相应集合中取值
if (list.size() > position) {
return list.get(position);
} else {
// 否则的话,就减去集合的大小,
position -= list.size();
}
}
return null;
}


分别从单个集合中分别取值打印如下:

A-List-------4
B-List-------1
C-List-------1


3,自定义View有时候需要滑动View的内容,比如滑动轮播图,

那么手机滑动过程中,突然离开,那么此时如何计算滑动到哪一个下标索引:

计算的算法是这样的:

int scrollX = getScrollX();
//手指离开的时候,当前滑到了第几个索引
index = (scrollX + mChildWidth / 2) / mChildWidth;
if (index < 0) {
index = 0;
} else if (index > mChildCount - 1) {
index = mChildCount - 1;
}


mChildWidth:是子View的宽度,mChildCount是子View的个数.

以宽度的1/2位计量标准,
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息