【问题标题】:Android: How to add buttons to GridView dynamically?Android:如何动态地将按钮添加到 GridView?
【发布时间】:2020-03-27 15:47:10
【问题描述】:

我正在尝试为 textArray 中的每个字符串向 GridView 添加按钮。

void addButtons() {

    GridView gridView = (GridView) findViewById(R.id.gridView);
    List<Button> buttons = new ArrayList<Button>();

    for (int i = 0; i < textArray.length; i++) {
        Button newButton = new Button(this);
        newButton.setText(textArray[i]);
        newButton.setId(i);
        newButton.setOnClickListener(onClickListener);

        buttons.add(newButton);
    }

    ArrayAdapter<Button> arrayAdapter = new ArrayAdapter<Button>
            (this, android.R.layout.simple_list_item_1, buttons);
    gridView.setAdapter(arrayAdapter);

}

但结果,我得到了这个:Virtual Device screen

有什么问题吗?或者也许有更好的方法来做同样的事情?我试过 LinearLayout,一切正常,但我无法向下滚动。

how to add button in gridview dynamically 可能有一个解决方案,但说实话,目前对我来说太难了。

【问题讨论】:

标签: android android-studio android-layout android-gridview


【解决方案1】:

试试这个,它展示了如何在运行时创建按钮https://forums.xamarin.com/discussion/49225/dynamic-buttons-in-gridview

【讨论】:

    【解决方案2】:

    所以最初的问题是通过程序生成的按钮获得一个视图。第一个解决方案是LinearLayout,但我发现我无法向下滚动它,所以按钮的数量是有限的。在互联网上,我发现 GridView 也可以完成这样的任务,并且可以滚动。嗯,这是真的,但我一直坚持这个帖子中提到的问题。

    经过几天的谷歌搜索,我发现 ScrollView 中的 LinearLayout 是我所需要的。所以这是我的 xml 和 java 代码,供偶然发现相同问题的人使用:

        <ScrollView
            <LinearLayout
                android:id="@+id/cityLayout"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:orientation="vertical">
                <!-- Content here -->
            </LinearLayout>
        </ScrollView>
    
    void addButtons() {
    
        LinearLayout linearLayout = findViewById(R.id.cityLayout);
    
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams
                (LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    
        for (int i = 0; i < cityArray.length; i++) {
            Button newButton = new Button(this);
            newButton.setText(cityArray[i]);
            newButton.setId(i);
            newButton.setOnClickListener(onClickListener);
    
            linearLayout.addView(newButton, layoutParams);
        }
    }
    

    不管怎样,谢谢大家的帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-04
      • 1970-01-01
      • 1970-01-01
      • 2010-09-29
      • 1970-01-01
      相关资源
      最近更新 更多