【发布时间】:2016-09-30 05:04:35
【问题描述】:
我对我正在做的一个练习有点卡住了。 我基本上有 4 个按钮,如果选中复选框,则必须隐藏一个。 我不知道为什么,但我就是不知道该怎么做,我应该制作一个 arrayList 而不是一个数组并不断删除/添加值,还是有另一种方法来“隐藏”或不使用值?
希望我的解释有点清楚,在此先感谢! :)
这是代码 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
}
}
});
}
}
【问题讨论】:
-
如果使用列表,不要使用数组列表,使用 LinkedList。原因 - ArrayList 内部仍然使用数组。从中间删除一些东西是低效的。 LinkedList 使用指针结构——它就像迭代的面一样,并且更容易从中删除东西。它的缺点是随机访问速度较慢。
-
@GabeSechan 哦,好吧!没听说过,到时候一定去看看,谢谢!
标签: java android arrays arraylist ischecked