【发布时间】:2010-04-30 19:51:23
【问题描述】:
我注意到很多 Android 函数都有一个可以传入的参数,它是一个位掩码,对于不同的选项,比如在 PendingIntent 上,你可以传入一些东西,比如你可以用PendingIntent.FLAG_CANCEL_CURRENT|PendingIntent.FLAG_NO_CREATE 调用 getActivity()。
我想知道如何创建一个具有这样参数的函数?
【问题讨论】:
我注意到很多 Android 函数都有一个可以传入的参数,它是一个位掩码,对于不同的选项,比如在 PendingIntent 上,你可以传入一些东西,比如你可以用PendingIntent.FLAG_CANCEL_CURRENT|PendingIntent.FLAG_NO_CREATE 调用 getActivity()。
我想知道如何创建一个具有这样参数的函数?
【问题讨论】:
public static final int FLAG_1 = 1<<0; // 0x01
public static final int FLAG_2 = 1<<1; // 0x02
public static final int FLAG_3 = 1<<2; // 0x04
public static final int FLAG_4 = 1<<3; // 0x08
public void myFlagsFunction( int flags ) {
if ( 0 != ( flags & FLAG_1 ) ) {
// do stuff
}
if ( 0 != ( flags & FLAG_2 ) ) {
// do stuff
}
}
【讨论】:
它们是手动完成的,只需将标志定义为 2 的幂。 This file 使用左移位运算符,但这不是必需的:
public static final int FLAG_ONE_SHOT = 1<<30;
//...
public static final int FLAG_NO_CREATE = 1<<29;
【讨论】:
当我们对一个int值做一次
现在 2 的所有正幂都是 1,2,4,8,16,32 , ...... , 1073741824 对于 int 值。 这些值在某个索引处的二进制表示中仅包含单个“1”。
这有一个利润,当你 | (按位或)任何两个 2 的幂,两个值的 '1' 对应索引在结果值中都设置为 '1'。
例如 8 (1000) 在索引 3 处有 1,而 2 (10) 在索引 1 处有 1,当我们 | (或)我们得到二进制的 1010,这意味着 1 和 3 索引位都设置为 1。
所以如果你想检查哪些标志被组合了,你只需要检查 '1' 的索引。
例如-
static int test0= 1;
static int test1= 2;
static int test2= 4;
static int test3= 8;
static int test4= 16;
static int test5= 32;
static int test6= 64;
int[] result;
int[] decision(int flags){
char[] x=Integer.toBinaryString(flags).toCharArray();
result=new int[x.length];
for(int i=x.length-1,j=0,k=0;i>=0;i--)
switch (x[k++]){
case '0':
break;
case '1':
if(i==0){
result[j++]=-1; //for ...000001 (test0) put -1 into the array instead of the value of i which is 0.
break;
}
result[j++]=i;
};
return result;
}
/* 例如,如果决策方法返回一个包含 {6,3,1,0,0,0} 的数组,那么这意味着 test6,test3 和 test1 标志是 or-ed ( decision(test6|test3|test1) )。 */
感谢上面的两个答案,我有一个问题,你提到的方法是如何工作的,我从上面的两个答案中得到了答案。实际的实现如前两个答案所示。
【讨论】: