【问题标题】:Create new button and add it in next position创建新按钮并将其添加到下一个位置
【发布时间】:2016-10-17 06:17:36
【问题描述】:

如何以编程方式创建按钮

Button x = new Button (this);

但是我将这个按钮添加到下一个可用位置。现在,如果我这样做并达到四个创建的按钮,第五个将在屏幕之外。如何让第五个检查右侧是否有足够的空间,如果没有,则在其余按钮下方创建按钮。

我尝试了网格布局并增加了列数,但它并不好,因为我想支持 Android 7。

【问题讨论】:

  • 滚动视图中的线性布局。向其中添加按钮

标签: java android


【解决方案1】:

您是否尝试创建或搜索FlowLayout。有很多 Github 回购。

我建议你看看这个问题:How can I do something like a FlowLayout in Android?

如果你去Github搜索这个,你可以找到例子:Github Flow Layout

您也可以搜索TagView 来学习如何创建自定义视图并动态添加它:Tag View

【讨论】:

  • 谢谢兄弟,这正是我需要的。
【解决方案2】:

尝试在布局中使用scrollView

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true">

【讨论】:

  • 还有其他方法吗?因为我想填满整个屏幕,所以如果我要创建 20 个正方形,我将有 5 行,每行有 4 个按钮,所有这些都是以编程方式完成的。
【解决方案3】:

将它们包裹在一个垂直的LinearLayout 中,然后添加它们的权重属性:

Button button = new Button(this);
button.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));

【讨论】:

  • 很好的思维方式,但这并不能解决问题。它只是在使用 no 滚动视图之前扩展了我可以添加的按钮数量,最终它们会离开屏幕。我不能检测到它们何时会超出屏幕或在使用权重的情况下太小,然后在这些按钮的右侧创建更多按钮吗?
【解决方案4】:

它很老套,但它有效?xml 中的 Main LinearLayout 是垂直方向的。 因此,它会根据屏幕宽度检查您生成的所有按钮的总宽度,如果大于或等于,它将创建一个水平方向的新线性布局并继续放入按钮。

这仅包含您要创建的按钮数量。

private void generateButton(int noOfButton){
        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        linearLayout.setOrientation(LinearLayout.HORIZONTAL);
        totalButtonWidth = 0;
        while(noOfButton!= 0){
            DisplayMetrics metrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metrics);
            int phoneWidth = metrics.widthPixels;
            button = new Button(this);
            button.setLayoutParams(new LinearLayout.LayoutParams(244,200));
            totalButtonWidth += 244;
            Log.i(TAG,"totalWidth"+totalButtonWidth);
            if(totalButtonWidth>=phoneWidth){
                totalButtonWidth = 244;
                linearLayoutMain.addView(linearLayout);
                linearLayout = new LinearLayout(this);
                linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT));
                linearLayout.setOrientation(LinearLayout.HORIZONTAL);
            }
            linearLayout.addView(button);
            noOfButton--;
        }
        linearLayoutMain.addView(linearLayout);
    }

【讨论】:

    猜你喜欢
    • 2018-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-10
    • 2012-07-08
    • 1970-01-01
    • 2021-01-24
    相关资源
    最近更新 更多