簡體   English   中英

以編程方式創建帶有 2 列按鈕的滾動視圖 Android Studio Java

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

我創建了一個滾動視圖,我以編程方式添加了可變數量的按鈕,但我現在必須這樣做,以便在滾動視圖中的每個按鈕旁邊都有第二個較小的按鈕。 這是我現在的屏幕: ![這是我現在的滾動視圖

我希望每個按鈕旁邊都有一個小按鈕,可以讓我刪除選項或類似的東西。

這是我現在必須構建按鈕的代碼

    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);
        }
    }

任何幫助將不勝感激。

不要為每個文件添加一個Button ,而是為每個文件添加一個完整的LinearLayout ,並具有水平方向。 然后,首先將帶有文件名的按鈕添加到此內部線性布局,然后是刪除按鈕(它們將連續出現)。

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++;
    }
}

您可能需要做一些額外的樣式設置,例如設置按鈕之間的距離,或者以某種方式對齊它們。 你也應該能夠以某種方式以編程方式做到這一點,但那是另一回事。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM