2012-05-04 190 views
0

我有一些Android開發經驗,但我完全失去了一個簡單的任務(至少看起來很簡單)。如何一個接一個地動態創建按鈕?

我有一個字符串的ArrayList,我想從佈局列表中的字符串創建按鈕。它不必是按鈕 - 它可以是任何可點擊的對象(包含文本)。

主要問題是我想要一個接一個地創建它們,當它們不適合屏幕時 - 應該創建新行。

正常線性佈局可以將它們排列爲水平,但不會創建新線。 我也嘗試了網格視圖和它的幾乎 - 但它是一個網格,所有colums都是相同的大小(但文本可以不同,所以我不喜歡它)。

任何想法如何做到這一點? 在此先感謝。

回答

1

Android中沒有流佈局。你必須實現你自己的自定義佈局(不是微不足道的),或者找到第三方流佈局。

+0

任何線索如何開始這個「不trival」解決方案? :) – Mark

+0

你可能試過谷歌搜索。以下是當我搜索Android流佈局時出現的兩個鏈接:[另一個SO問題](http://www.stackoverflow.com/questions/4474237/how-can-i-do-something-like-a-flowlayout -in-android)和[GitHub項目](https://github.com/ApmeM/android-flowlayout)。 – kabuko

1

你可以嘗試這樣的事情。

// get the width of the screen 
Display display = getWindowManager().getDefaultDisplay(); 
int windowWidth = display.getWidth(); 

// keep track of the width of your views on the current row 
int cumulativeWidth = 0; 

// the width of your new view 
int newWidth = // insert some number here based on the length of text. 

// get your main layout here 
ViewGroup main = (ViewGroup)findViewById(R.id.YOUR_HOLDING_LAYOUT); 

// the linear layout holding our views 
LinearyLayout linear = null; 
// see if we need to create a new row 
if (newWidth + cumulativeWidth > windowWidth){ 
    linear = new LinearLayout(this); 
    // set you layout params, like orientation horizontal and width and height. This code may have typos, so double check 
    LayoutParams params = new LayoutParams(LinearLayout.FILL_PARENT, LinearLayout.WRAP_CONTENT); 
    params.setOrientation(HORIZONTAL); // this line is not correct, you need to look up how to set the orientation to horizontal correctly. 
    linear.setParams(params); 
    main.addView(linear); 
// reset cumulative width 
cumulativeWidth = 0; 
} 

// no create you new button or text using newWidth 
View newView = ... // whatever you need to do to create the view 

linear.addView(newView); 

//keep track of your cumulatinv width 
cumulativeWidth += newWidth; 
+0

這可能會工作,但這裏最大的問題是: 「int newWidth = //根據文本的長度在這裏插入一些數字。」 當您使用dpi而不是px作爲單位時,這將在不同的顯示器上以不同的方式工作。你可能能夠計算出這個數字,但可能會有一個屏幕/ dpi,你會得到一半的按鈕在行末:) – Mark