2011-12-30 69 views
1

我試圖TableRow的addView()如何工作?

private void addSnapPictureRow(TableLayout table, Bitmap bitmap) { 
     /* 
     * 1st row = TextView (Check In) 
     */ 
     TableRow row = new TableRow(this); 
     row.setGravity(Gravity.CENTER_HORIZONTAL); 
     // add text 
     TextView text = new TextView(this); 
     text.setText("Snap Picture"); 
     TableRow.LayoutParams textLayoutParams = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT); 
     textLayoutParams.setMargins(100, 0, 0, 0); 
     row.addView(text, textLayoutParams); 

     // add picture 
     ImageView picture = new ImageView(this); 
     picture.setImageResource(R.drawable.adium); 
     row.addView(picture); 

     /* 
     * 2nd row = View (separator) 
     */ 
     TableRow separator = new TableRow(this); 
     View line = new View(this); 
     TableRow.LayoutParams separatorLayoutParams = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, 1); 
     separatorLayoutParams.setMargins(100, 0, 0, 0); 
     line.setBackgroundColor(Color.BLUE); 
     separator.addView(line, separatorLayoutParams); 

     // add row to table 
     table.addView(row); 
     // add a separator 
     table.addView(separator); 
    } 

但是畫面一直沒有露面。如果我將重力改變爲CENTER_HORIZONTAL,那麼它只顯示圖片的一小部分。

enter image description here

當創建XML表,我想它會自動水平對齊。我無法理解TableRow佈局是如何工作的。任何人都可以向我提供一些啓示嗎?

回答

2

爲每行添加額外的LinearLayout解決了我的問題;)。前一行的排列會導致圖片不在屏幕上。

private void addSnapPictureRow(TableLayout table, Bitmap bitmap) { 
     /* 
     * 1st row = TextView (Check In) 
     */ 
     TableRow row = new TableRow(this); 
     LinearLayout outerLayout = new LinearLayout(this); 
     // add text 
     TextView text = new TextView(this); 
     text.setText("Snap Picture"); 
     LinearLayout.LayoutParams textLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); 
     textLayoutParams.setMargins(100, 0, 0, 0); 

     // add picture 
     ImageView picture = new ImageView(this); 
     LinearLayout.LayoutParams pictureLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); 
     picture.setImageResource(R.drawable.adium); 
     pictureLayoutParams.setMargins(20, 0, 0, 0); 

     outerLayout.addView(text, textLayoutParams); 
     outerLayout.addView(picture, pictureLayoutParams); 
     row.addView(outerLayout); 

     /* 
     * 2nd row = View (separator) 
     */ 
     TableRow separator = new TableRow(this); 
     View line = new View(this); 
     TableRow.LayoutParams separatorLayoutParams = new TableRow.LayoutParams(400, 1); 
     separatorLayoutParams.setMargins(100, 0, 0, 0); 
     line.setBackgroundColor(Color.BLUE); 
     separator.addView(line, separatorLayoutParams); 

     // add row to table 
     table.addView(row); 
     // add a separator 
     table.addView(separator); 
    }