0

私は自分が作っているエクササイズに少し行き詰まっています。基本的に 4 つのボタンがあり、チェックボックスがオンになっている場合は 1 つを非表示にする必要があります。理由はわかりませんが、これを行う方法がわかりません。配列の代わりに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
                }
            }
        });
    }
}
4

1 に答える 1

1

たくさんのオプションがあります。提案したように 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)

于 2016-09-29T21:04:35.220 に答える