【问题标题】:Layouts and Button布局和按钮
【发布时间】:2017-09-23 17:32:54
【问题描述】:
TableLayout relativeLayout = (TableLayout)findViewById(R.id.ll1);
        TableRow row =new TableRow(this); 
        Button button ;
        int counter = 0;

        for(int i = 0;i<=13;i++){
                counter++;
                button = new Button(this);
                button.setText(counter);


                row.addView(button);

            }

        relativeLayout.addView(row,new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
        relativeLayout.computeScroll();             

XML 文件

<TableLayout android:id="@+id/ll1"  android:shrinkColumns="true"
        android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/button1"
        xmlns:android="http://schemas.android.com/apk/res/android"></TableLayout>

但是每当我执行我的应用程序时,它只会将我的按钮移动到一行中,并且在 5 个按钮之后,所有按钮都会从屏幕上移出。我不想添加更多行,因为我不想在我的代码中硬编码任何东西,比如放置一些代码 if (counter%5==0) 然后做这个和那个。

是否有任何其他方法来计算宽度,如果按钮等于屏幕宽度,则执行此或那个或任何其他方式,如表格布局中的任何属性,只需包装一行的内容?

【问题讨论】:

  • 如果您只有一行,请使用 LinearLayout!我不明白你到底想做什么?当您将按钮添加到布局时会发生什么,它们应该如何出现在屏幕上 - 单行,多行???

标签: android layout tablelayout


【解决方案1】:

是的,有一种方法可以获取应用中任何组件的确切宽度。看看我对我不久前提出的问题的回答here。如您所见,我实例化了一个 Paint 对象,但除非您希望获得文本本身的宽度,否则这不是必需的。但是,您必须使用密度乘数:

float scale = getContext().getResources().getDisplayMetrics().density;

这会将获取组件(在本例中为您的按钮)宽度的任何函数转换为任何给定设备上的实际像素宽度。因此,您将获得按钮宽度(通过在 Button 对象上调用 getWidth() 函数),然后乘以该比例因子。

【讨论】:

    【解决方案2】:
    【解决方案3】:

    使用Contex 的方法getResources(),您可以访问应用程序包的所有资源。该方法返回Resources,您可以看到here所有可用的属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-07
      • 2021-09-24
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 2011-01-31
      • 1970-01-01
      相关资源
      最近更新 更多