2011-12-29 98 views
2

我在我的XML中有一個TableLayout,我想動態地添加一個TableLow與ImageView到該TableLayout。我到目前爲止是這樣的:動態添加ImageView到TableRow

TableRow tr = new TableRow(this); 
ImageView imgView = new ImageView(this); 
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
          LayoutParams.WRAP_CONTENT, 
          LayoutParams.WRAP_CONTENT); 
imgView.setLayoutParams(lp); 
imgView.setImageDrawable(getResources().getDrawable(R.drawable.icon_test)); 
tr.addView(imgView); 
tlCollection.addView(tr); 

我在做什麼錯了?如果我想一個TextView添加到相同的TableRow,它的工作原理,但加入了ImageView的不工作..

的代碼添加一個TextView:

TextView myTextView = new TextView(this); 

myTextView.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.FILL_PARENT,TableRow.LayoutParams.WRAP_CONTENT)); 
myTextView.setText("Test"); 
tr.addView(myTextView); 

任何想法?

回答

0

我固定它,使用LayoutInflater:

LayoutInflater inflater = getLayoutInflater(); 

TableRow row = (TableRow)inflater.inflate(R.layout.collection_row, tlCollection, false); 

//fill textview 
TextView content = (TextView)row.findViewById(R.id.txtCollection); 
content.setText("Test"); 

//fill imageview 
ImageView myImgView = ImageView)row.findViewById(R.id.imgCollection);   
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.my_icon)); 

//add row to tablelayout 
tlCollection.addView(row); 
0

我認爲它與佈局參數有關。您將兩個維都設置爲WRAP_CONTENT,但圖像視圖本身不具有「內容」,它具有可繪製的源。嘗試玩adjustViewBounds,setScaleType和佈局參數。注意在你能夠添加TextView的例子中,你將寬度設置爲FILL_PARENT?

我在這種方式下動態添加ImageView的開放項目中能夠快速找到的唯一示例是我在兩個方向上都使用FILL_PARENT的情況。這可能對你不起作用,因爲我沒有完全一樣,但是值得玩弄這些設置以及上面提到的其他兩個設置。

+0

也不起作用。我將它們都設置爲FILL_PARENT,但圖像仍未顯示。任何其他想法?問題是,當我加的TableRow與XML一個TextView和ImageView的,它的工作: harmjanr 2011-12-30 12:49:18

0

嘗試這種

ImageView的imgView =新ImageView的(本); imgView.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher));

tr.addView(imgView);

0

我有同樣的問題,現在其上的使用下面的代碼

CandFlag =new ImageView(this); 
CandFlag.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, 
        TableRow.LayoutParams.WRAP_CONTENT)); 

CandFlag.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.flag)); 


LayoutParams layoutParams = (LayoutParams) CandFlag.getLayoutParams(); 
      layoutParams.width = 75; 
      layoutParams.height = 75; 
      CandFlag.setLayoutParams(layoutParams); 

Tablerow.addView(CandFlag);