我有一个关于使用按钮切换一些图像的教程,这是代码
public class MainActivity extends AppCompatActivity {
private static ImageView andro;
private static Button buttonswitch;
int current_image_index = 0;
int[] images = {R.mipmap.andro_img,R.mipmap.apple_image,R.mipmap.ic_launcher,R.mipmap.ic_launcher_round};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonClick();
}
public void buttonClick() {
andro = (ImageView) findViewById(R.id.imageView);
buttonswitch = (Button) findViewById(R.id.button);
buttonswitch.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
current_image_index++;
current_image_index = current_image_index % images.length;
andro.setImageResource(images[current_image_index]);
}
}
);
}
}
这部分我真的很困惑:
@Override
public void onClick(View view) {
current_image_index++;
current_image_index = current_image_index % images.length;
andro.setImageResource(images[current_image_index]);
我的理解是,一旦单击按钮,int current_image_index 将增加 1。然后对 current_image_index 与 images.length 进行模运算,将 current_image_index 的余数除以 image.length。例如,第一次我会让current_image_index = 0,然后一旦点击,它就会是1,然后current_image_index % image.length = 0。然后andro.setImageResource(images[0]);
如此循环往复,current_image_index始终为0。那么current_image_index%image.length总是为0,点击图片怎么会不断变化呢?
最佳答案
...since the current_image_index%image.length will always give a result of 0.
不太正确。
模运算符 ( %
) 计算 remainder两个操作数。这是一种重复的减法。事实上,与 a % b
你会问自己:
What number remains if I repeat subtracting
b
froma
until that operation is no longer possible?
让我们用 8 % 3
来测试它(所以 a = 8
和 b = 3
)。
- 我可以从 8 中减去 3 吗?是的,结果是 5。
- 我可以从 5 中减去 3 吗?是的,结果是 2。
- 我可以从 2 中减去 3 吗? 否,所以我们的最终结果是 2。
逻辑上,操作 a % b
结果r
总是结果 0 <= r < b
.
Examples:
5 % 2 = 1 (because 4 ÷ 2 = 2 and the remainder is 1)
17 % 6 = 5 (because 12 ÷ 6 = 2 and the remainder is 5)
20 % 4 = 0 (because 20 ÷ 4 = 5 and nothing remains)
因此,在您的情况下,数组索引始终至少为 0
最多images.length - 1
。这正是数组的有效范围。
假设您有 3 张图像,因此 images.length
是3。另外current_image_index
初始化为0。所以你会看到image[0]
在开始时。
- 您点击一次,因此
current_image_index
增加到1
。然后,应用模运算:1 % 3 = 1
. - 您再次点击,因此
current_image_index
增加到2
。然后,应用模运算:2 % 3 = 2
. - 您再次点击,因此
current_image_index
增加到3
。然后,应用模运算:3 % 3 = 0
。这意味着索引达到 3,但随后立即被模运算符重置为 0。
所以在image[2]
之后, image[0]
显示。您会看到从 0 而不是 1 开始的索引现在对我们有利。
关于java - 数组索引的模运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44772011/