0

I am making an Android piano app (my first) and here is my problem. I want to change the number of piano keys by pressing a specific button. Keys are declared as arrays

Button[] whiteKeys = new Button[8];

For the keys I am using View.OnClickListener

View.OnClickListener btnClicked = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        switch(v.getId())
        {
            case 1:
                 //Here I want to change the length of my whiteKeys array from 8 to 16}  

How can I do that? I am completly new to Java so this may be a bit noobish question.

2
  • 4
    You can't increase the size of an array... You have to make a new array Commented May 5, 2017 at 19:56
  • 2
    the size of an array is fixed you can use List or ArrayList in which you can dynamically change the contents of ArrayList Commented May 5, 2017 at 20:02

3 Answers 3

3

In Java, there is a thing called an ArrayList. It gives methods for accessing it like an array or a list. So adding a key is just list.add(key) or list.add(index, key), remove with list.remove(list.size() - 1), and then get with list.get(key_number).

Of course, you can also just initialize your key array to MAX_KEYS (where MAX_KEYS is a constant you define for most keys you will allow on your keyboard, and then you just have to track which keys are visible)

P.S.
You may also want to become familiar with the synchronize key word. In your example, you don't strictly need it, but ArrayList is not thread safe. (so spamming it may cause weird things)

Sign up to request clarification or add additional context in comments.

Comments

1

If you don't want to use an ArrayList, you can still do this using arrays.

One obvious try is:

whiteKeys = new Button[16];

Now your array has 16 elements. The problem is that you just wiped out whatever was in the old array. To prevent that, we can first copy it over to a new array. So instead, you'd do this:

Button[] temp = new Button[16];
System.arraycopy(whiteKeys, 0, temp, 0, whiteKeys.length);
whiteKeys = temp;

Comments

0

Arrays in Java are size fixed, so you will have to either declare a new Array or use a dynamic structure like ArrayList. Using ArrayList you can call .get(index), .add(newButton) and .remove(index).

Make sure to add your new Buttons in the main thread. In this case your public void onClick(View v) is running in the main thread, but for better performance you can also add all the piano keys from the beginning and modify only the visibility:

pianoKey.setVisibility(View.VISIBLE);
pianoKey.setVisibility(View.INVISIBLE);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.