2012-04-06 89 views
0

1.这是我的代码,我尝试使用表格布局来显示按钮矩阵。我也尝试使这个矩阵屏幕独立,但是这不能正常工作。在大尺寸模拟器中,它会让问题按钮重叠。如何使表格布局独立于屏幕

 TableLayout layout = new TableLayout (this); 
    layout.setStretchAllColumns(true); 
    Display display = ((WindowManager)  getSystemService(WINDOW_SERVICE)).getDefaultDisplay(); 
      int width = display.getWidth(); 
      int height = display.getHeight(); 
      layout.setLayoutParams(new TableLayout.LayoutParams(height,width)); 

      layout.setPadding(1,1,1,1); 

      for (int f=0; f<=3; f++) 
      { 
       TableRow tr = new TableRow(this); 

       for (int c=0; c<=3; c++) 
       { 
        Button b = new Button (this); 
        b.setText(""+f+c); 
        b.setTextSize(10.0f); 
        b.setTextColor(Color.rgb(100, 200, 200)); 



        tr.addView(b,30,30); 


        final float scale = getBaseContext().getResources().getDisplayMetrics().density; 
        int pixels = (int) (dps * scale + 0.5f); 
        b.setHeight(pixels); 
        b.setWidth(pixels); 


       } // for 
       layout.addView(tr); 
      } // for 

      super.setContentView(layout); 
     } 

     } 

回答

1

您正在以奇怪的方式设置布局参数。尝试使用:

layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); 

与按钮相同的问题。尝试使用此:

Button b = new Button (this); 

LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, 
      LayoutParams.WRAP_CONTENT); 
params.gravity = Gravity.CENTER; // if you want it centered 
params.span = 1; 

b..setLayoutParams(params); 

b.setText(""+f+c); 
b.setTextSize(10.0f); 
b.setTextColor(Color.rgb(100, 200, 200)); 

tr.addView(b); 

而不要使用“比例”设置高度和宽度值。 params.span = 1;部分应该为您的表格行中的每个元素提供相同的宽度。 而params.gravity = Gravity.CENTER;将它置于表格单元中。

或者你可以使用GridLayout。在这里看到︰New Layout Widgets: Space and GridLayout

+0

+1表示GridLayout。 – 2012-04-06 09:24:02

+0

@PareshMayani非常感谢你,我的初学者你的解决方案帮助了我很多 – pragati 2012-04-06 16:40:51