Search code examples
javaandroidandroid-studiobuttonandroid-linearlayout

Programmatically create a scrollview with 2 columns of buttons Android Studio Java


I have a scrollview created that I add a variable amount of buttons to programmatically, but I now have to make it so that I have a second smaller button beside each of the buttons within the scrollview. Here is my screen now: ![Here is my scrollview now

I would like there to be a small button beside each of those that would let me delete the option or something along those lines.

Here is my code I have now to build the buttons

    public void addButtons() {
        LinearLayout linearLayout = findViewById(R.id.loadLinearLayout);

        int i = 0;
        for(File file : files) {
            Button newButton = new Button(this);
            String filename = file.getName();
            newButton.setId(i);
            newButton.setText(filename);
            newButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    loadGame(view.getId());
                }
            });
            i++;

            linearLayout.addView(newButton);
        }
    }

Any help would be greatly appreciated.


Solution

  • Instead of adding a Button for each file, add a whole LinearLayout for each of them, with horizontal orientation. Then, add to this inner linear layout first the button with the file name, then the delete button (they will appear in a row).

    public void addButtons() {
        LinearLayout linearLayout = findViewById(R.id.loadLinearLayout);
    
        int i = 0;
        for(File file : files) {
            //create horizontal linear layout
            LinearLayout innerLayout = new LinearLayout(this);
            innerLayout.setOrientation(LinearLayout.HORIZONTAL);
    
            Button newButton = new Button(this); //button which shows file name
            String filename = file.getName();
            newButton.setId(i);
            newButton.setText(filename);
            newButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    loadGame(view.getId());
                }
            });
            innerLayout.addView(newButton);
    
            Button deleteButton = new Button(this);
            deleteButton.setText("Delete"); //use a string resource ideally
            innerLayout.addView(deleteButton);
    
            linearLayout.addView(innerLayout); //add the inner layout to the outer
            i++;
        }
    }
    

    You might need to do some additional styling, such as set the distance between the buttons, or align them in a way. You should also be able to do that programmatically somehow, but that is a different story.