我想制作一个简单的应用程序(在Android studio中),可以使用一个按钮更改图像,每个按钮随意按下不同的图像。我只知道如何改变一张照片只有一个按钮,这个代码我怎样才能用一个按钮来改变我的imageView src,但随机的几张图片呢?
thatImage.setImageResource(R.drawable.myimage);
但我不知道如何有准备取代它的多个图像时,用户按下按钮和随机。所以,如果有人可以帮助我这个我将不胜感激,谢谢大家的支持:)
我想制作一个简单的应用程序(在Android studio中),可以使用一个按钮更改图像,每个按钮随意按下不同的图像。我只知道如何改变一张照片只有一个按钮,这个代码我怎样才能用一个按钮来改变我的imageView src,但随机的几张图片呢?
thatImage.setImageResource(R.drawable.myimage);
但我不知道如何有准备取代它的多个图像时,用户按下按钮和随机。所以,如果有人可以帮助我这个我将不胜感激,谢谢大家的支持:)
您创建图像的数组,然后用随机数,让他们中的一个:
int[] myImageList = new int[]{R.drawable.image1, R.drawable.image2...};
Random random = new Random();
Integer rand = random.nextInt(myImageList.length - 1) + 0;
thatImage.setImageResource(myImageList[rand]);
strings.xml中
<array name="myImages">
<item>@drawable/a</item>
<item>@drawable/b</item>
<item>@drawable/c</item>
<item>@drawable/d</item>
<item>@drawable/e</item>
</array>
为主要活动
公共类MainActivity扩展AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn=(Button)findViewById(R.id.btn);
final RelativeLayout background = (RelativeLayout) findViewById(R.id.back);
Resources res = getResources();
final TypedArray myImages = res.obtainTypedArray(R.array.myImages);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Random random = new Random();
int randomInt = random.nextInt(myImages.length());
int drawableID = myImages.getResourceId(randomInt, -1);
background.setBackgroundResource(drawableID);
}
});
}
thx求助 – Joshua