I'm a bit stuck with an exercise I'm making. I basically have 4 buttons and have to hide one if a checkbox is checked. I don't know why but I just can't figure out how to do this, should I make an arrayList instead of an array and remove/add the value constantly or is there another way to 'hide' or not use a value?
Hope my explanation is a bit clear, thanks in advance! :)
Here's the code MainActivity.java code (not including imports):
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
}
}
});
}
}
You have tons of options. You can use an ArrayList like you suggested, you can pass the list of available colors to the setColor
method. Maybe you can pass the color you don't want to use and then when randoming do if(randomedColor == colorYouDontWant) then random again
. You can even use Map<String, Color>
and put all the colors in there and then just delete them from this map, randoming would be quite weird tho. Or Map<String, Boolean>
where key would be color and value would be if color is available or not (true if available, false otherwise). I suggest using ArrayList.
btw. this fragment:
if(rndColor2 == rndColor){
rndColor2 = randomColor(colors.length);
}
I understand that you don't want colors to be the same, but what if randoming again is gonna give the same result? You should do:
while(rndColor2 == rndColor)