android - 将按钮垂直和水平放置在 LinearLayout 中

标签 android android-layout android-studio

我是 Android 编程新手,正在使用最新版本的 Android Studio。

我有一个 LinearLayout 并希望以编程方式放置 20 个按钮。

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
for (int i = 0; i<20;i++)
{
  Button btn = new Button(this);
  btn.setText("Button" + (i + 1));
  btn.setTag(i + 1);
  btn.setLayoutParams (new LinearLayout.LayoutParams(200, LinearLayout.LayoutParams.WRAP_CONTENT,1));
  btn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
         Toast.makeText(getApplicationContext(), view.getTag().toString(), Toast.LENGTH_SHORT).show();
           }
        });
        linearLayout.addView(btn);
 }

我正在使用这段代码。它逐一添加了 20 个按钮。不过我想这样放置它们:

Button1 Button2
Button3 Button4
...
Button19 Button20

是否可以使用LinearLayout或者我应该使用不同类型的布局?

最佳答案

仅使用一个 LinearLayout 无法做到这一点。

要实现此目的,您必须使用:

TableLayout , GridView ,或(与这两个相比并不理想)水平 LinearLayout 内有 2 个垂直 LinearLayout

关于android - 将按钮垂直和水平放置在 LinearLayout 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23387864/

相关文章:

java - 将 Eclipse 项目导入 Android Studio : Google Maps API

android-studio - Android Studio会关闭此警告,而不是禁止显示:PARAMETER_NAME_CHANGED_ON_OVERRIDE

java - 敲击时放慢速度?

android - 在 Android 应用程序中启动 Google Firebase Analytic 实例的最佳方式是什么?

java - Android:使应用程序适应小屏幕布局,包括其他布局

Android XML 有没有办法将工具命名空间与自定义属性一起使用?

Android - TextView 向上推 Imageview

java - Google map 不适用于带有 proguard 的发布版本

android - 使用当前版本检查 Plays 商店版本并显示更新对话框

android - APK META-INF/maven/com.squareup/otto/pom.xml 中复制的重复文件