[英]Android dynamically Add multiple buttons
我試圖在Android中動態添加按鈕,但是我使用的方法只是顯示循環的最后一個按鈕。
這是我正在使用的代碼:
for(int i = 0; i < SavedProducts.brands.size(); i++){
Button btn = new Button(getActivity());
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 250);
layoutParams.setMargins(80, 60, 80, 0);
btn.setLayoutParams(layoutParams);
btn.setText(SavedProducts.brands.get(i).Name);
Log.e("DISPLAYING NAME", SavedProducts.brands.get(i).Name+"");
brandsList.addView(btn);
}
使用此代碼時,我僅在屏幕頂部得到一個按鈕。 我的猜測是它們正在彼此堆疊。 如何使按鈕堆疊在彼此下方?
謝謝。
在此上下文中,brandsList是RelativeLayout。 已正確填充SavedProducts對象。
編輯:我不確定是否會有所作為,但我試圖在片段內執行此操作
我的問題是在此行設置邊距:
layoutParams.setMargins(80, 60, 80, 0);
此函數的參數為setMargins(左邊緣,上邊緣,右邊緣,下邊緣)。
盡管我是動態添加按鈕的,但我並沒有更改每個按鈕的邊距,因此它們都從試圖添加它們的視圖頂部出現了60像素。
為了解決這個問題,我做了一個新的變量
int topMargin = i * 270;
由於每個按鈕的高度為250,因此每個按鈕之間留有20像素的邊距。
然后,將新變量放入setMargins()函數中:
layoutParams.setMargins(80, topMargin, 80, 0);
這使得按鈕按我的意願出現在彼此下方。
在循環外創建按鈕數組,然后將其添加到布局中。
Button btn[] =new Button[SavedProducts.brands.size()];
for(int i = 0; i < SavedProducts.brands.size(); i++){
btn[i]=new Button () ;
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 250);
layoutParams.setMargins(80, 60, 80, 0);
btn[i].setLayoutParams(layoutParams);
btn[i].setText(SavedProducts.brands.get(i).Name);
Log.e("DISPLAYING NAME", SavedProducts.brands.get(i).Name+"");
brandsList.addView(btn[i] );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.