2014-09-22 78 views
0

我試圖設計一個簡單的應用程序,該應用程序水平滾動並使用圖像按鈕填充。使用自定義類對象填充線性佈局

我能夠填充列表,但只有手動有6個按鈕。難道沒有辦法通過數組和循環來做到這一點嗎?它感覺笨重使用btn,btn1,btn2等。

我linearList作爲mLinearList

我沒有設置onClickListeners還引用。

private void fillPaintingGallery() { 

     ImageButton btn = new ImageButton(this); 
     btn.setImageDrawable(getResources().getDrawable(R.drawable.painting1)); 
     mLinearList.addView(btn); 

     ImageButton btn1 = new ImageButton(this); 
     btn1.setImageDrawable(getResources().getDrawable(R.drawable.painting2)); 
     btn1.setContentDescription(RenaissanceDatabase.description[1]); 
     mLinearList.addView(btn1); 

     ImageButton btn2 = new ImageButton(this); 
     btn2.setImageDrawable(getResources().getDrawable(R.drawable.painting3)); 
     btn2.setContentDescription(RenaissanceDatabase.description[2]); 
     mLinearList.addView(btn2); 

     ImageButton btn3 = new ImageButton(this); 
     btn3.setImageDrawable(getResources().getDrawable(R.drawable.painting4)); 
     btn3.setContentDescription(RenaissanceDatabase.description[3]); 
     mLinearList.addView(btn3); 

     ImageButton btn4 = new ImageButton(this); 
     btn4.setImageDrawable(getResources().getDrawable(R.drawable.painting5)); 
     btn4.setContentDescription(RenaissanceDatabase.description[4]); 
     mLinearList.addView(btn4); 

     ImageButton btn5 = new ImageButton(this); 
     btn5.setImageDrawable(getResources().getDrawable(R.drawable.painting6)); 
     btn5.setContentDescription(RenaissanceDatabase.description[5]); 
     mLinearList.addView(btn5); 





    } 

感謝

回答

1

你爲什麼不使用的GridView或ListView您的需求

for (int i = 0; i < RenaissanceDatabase.description[].length; i++) { 
     ImageButton btn = new ImageButton(this); 
     int id = getResources().getIdentifier("yourpackagename:drawable/painting" + (i+1), null, null); 
     btn.setImageDrawable(getResources().getDrawable(
       id)); 
     btn.setContentDescription(RenaissanceDatabase.description[i]); 
     mLinearList.addView(btn); 

    } 
0

做的是有一個ListView和一個適配器,你想要什麼的對 'Android' 的方式。 ListView是容納項目列表的容器。適配器控制正在顯示的內容以及它的顯示方式。

這是關於如何填充列表的good example。您將修改示例,以便模板視圖包含ImageButton,並且該模型將具有圖像uri和描述。

相關問題