2011-08-10 227 views
0
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)然后执行此操作。

是否有任何其他的方法来计算的宽度,如果按键相当于屏幕的宽度,然后做这样或那样的或类似的表布局的任何财产只是换行的内容的任何其他方式?

+0

如果你只有一行,使用LinearLayout!我实际上不明白你想做什么?将按钮添加到布局时应该发生什么,它们应该如何显示在屏幕上 - 单行,多行? – nenito

回答

0

是的,有一种方式来获得任何组件的精确宽度在你的应用程序。看看我刚刚提出的问题here。正如你所看到的,我实例化了一个Paint对象,但除非你想获得文本本身的宽度,否则这不是必需的。然而,你必须使用密度倍增:

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

这将是获取组件宽度的任何功能(在这种情况下,您的按钮)转换成实际的像素宽度在任何给定的设备。所以你会得到按钮宽度(通过调用你的Button对象的getWidth()函数),然后乘以该比例因子。

0

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