我正在做的练习有点卡住了。我基本上有4个按钮,必须隐藏一个,如果一个复选框被选中。我不知道为什么,但我只是不知道如何做到这一点,我应该做一个数组列表,而不是一个数组和删除/添加值不断或有另一种方式来"隐藏"或不使用一个值?
希望我的解释是有点清楚,提前感谢!:)
下面是MainActivity.java代码(不包括导入):public class MainActivity extends AppCompatActivity {
String globalColor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setColor();
}
private int randomColor(int length){
return (int) Math.floor(Math.random()*length);
}
private void setColor(){
String [] colors = {"Green", "Blue", "Red", "Magenta"};
//ArrayList<String> colors = new ArrayList<String>();
int rndColor = randomColor(colors.length); //color name for text
int rndColor2 = randomColor(colors.length); //color for text color
if(rndColor2 == rndColor){
rndColor2 = randomColor(colors.length);
}
globalColor = colors[rndColor];
TextView v = (TextView) findViewById(R.id.color);
v.setText(colors[rndColor]);
v.setTextColor(Color.parseColor(colors[rndColor2]));
}
public void checkColor(View v){
Button b = (Button)v;
String buttonText = b.getText().toString();
TextView txtview = (TextView) findViewById(R.id.result);
if(buttonText.equals(globalColor)){
txtview.setText("Yaay");
setColor();
} else {
txtview.setText("Booo");
setColor();
}
}
private void hideMagenta(){
CheckBox checkbox = (CheckBox)findViewById(R.id.checkbox);
checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(isChecked){
//this is where my problem is; I want to remove magenta as an option
//is it better to do this with an arraylist and to remove and add magenta to the arraylist
//or is there a different, more efficient way
}
}
});
}
}
你有很多选择。你可以像你建议的那样使用ArrayList,你可以将可用颜色的列表传递给setColor
方法。也许你可以通过你不想使用的颜色,然后在随机时做if(randomedColor == colorYouDontWant) then random again
。你甚至可以使用Map<String, Color>
,把所有的颜色放在那里,然后从地图上删除它们,随机化会很奇怪。或者Map<String, Boolean>
,其中键是颜色,值是颜色是否可用(如果可用则为true,否则为false)。我建议使用ArrayList。
顺便说一句。这个片段:
if(rndColor2 == rndColor){
rndColor2 = randomColor(colors.length);
}
我明白你不希望颜色相同,但如果再次随机会得到相同的结果呢?你应该这样做:
while(rndColor2 == rndColor)