在Array或ArrayList(高效)Android/Java中删除和添加值
我有点被我正在做的运动困住了。 我基本上有4个按钮,如果选中复选框,我必须隐藏一个按钮。 我不知道为什么,但我就是不知道怎么做,我应该制作一个arrayList而不是一个数组,并不断删除/添加值,还是有其他方法“隐藏”或不使用值
希望我的解释有点清楚,提前谢谢!:)
以下是活动的代码。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
}
}
});
}
}
# 1 楼答案
你有很多选择。您可以像建议的那样使用ArrayList,您可以将可用颜色列表传递给
setColor
方法。也许你可以传递你不想使用的颜色,然后在随机化时做if(randomedColor == colorYouDontWant) then random again
。你甚至可以使用Map<String, Color>
把所有的颜色都放进去,然后把它们从地图上删除,随机化会很奇怪。或者Map<String, Boolean>
,其中键是颜色,值是颜色是否可用(如果可用,则为true,否则为false)。我建议使用ArrayList顺便说一句,这个片段:
我知道你不希望颜色是一样的,但是如果再次随机会得到相同的结果呢?你应该做:
while(rndColor2 == rndColor)