gpt4 book ai didi

java - 有没有办法通过键从 HashMap 中随机选择值?

转载 作者:行者123 更新时间:2023-11-29 05:08:24 25 4
gpt4 key购买 nike

<分区>

假设我有两个ImageButtons,一个HashMap,还有drawable(resources)中的图片作为一个值放在这个HashMap中。我需要使用 Randomizer 按键从 HashMap 中随机选择一个值,然后将此值(即图片)分配给 ImageButton 作为背景。例如,如果第一个按钮被点击,第二个按钮的背景将随机改变。

所以这是我已经拥有的:

public class MainActivity extends Activity {

final Resources res = getResources();
final Random random = new Random();

final ImageButton imgButt1 = (ImageButton) findViewById(R.id.imageButton1);
final ImageButton imgButt2 = (ImageButton) findViewById(R.id.imageButton2);

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Drawable coub1 = res.getDrawable(R.drawable.coub1);
Drawable coub2 = res.getDrawable(R.drawable.coub2);
Drawable coub3 = res.getDrawable(R.drawable.coub3);
Drawable coub4 = res.getDrawable(R.drawable.coub4);
Drawable coub5 = res.getDrawable(R.drawable.coub5);
Drawable coub6 = res.getDrawable(R.drawable.coub6);
Drawable coub7 = res.getDrawable(R.drawable.coub7);
Drawable coub8 = res.getDrawable(R.drawable.coub8);
Drawable coub9 = res.getDrawable(R.drawable.coub9);
Drawable coub10 = res.getDrawable(R.drawable.coub10);

final Map<Integer,Object> someHashMap = new HashMap<Integer,Object>();
someHashMap.put(1, coub1);
someHashMap.put(2, coub2);
someHashMap.put(3, coub3);
someHashMap.put(4, coub4);
someHashMap.put(5, coub5);
someHashMap.put(6, coub6);
someHashMap.put(7, coub7);
someHashMap.put(8, coub8);
someHashMap.put(9, coub9);
someHashMap.put(10, coub1);

imgButt1.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

Object[] values = someHashMap.values().toArray();
Object randomValue = values[random.nextInt(values.length)];
int drawableID = values.;
imgButt2.setBackgroundResource(drawableID);
}
});

imgButt2.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

Object[] values = someHashMap.values().toArray();
Object randomValue = values[random.nextInt(values.length)];
int drawableID = myImages.getResourceId(randomInt, -1);
imgButt1.setBackgroundResource(drawableID);
}
});
}
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com