我有以下代码:
LinearLayout lyt = (LinearLayout)findViewById(R.id.mylayout);
for(i=0;i<=3 ;i++) {
ImageButton ib= new ImageButton(this);
BitmapDrawable imagebd;
ib.setClickable(true);
imageid = getResources().getIdentifier("drawable/" + image,null,getPackageName());
ib.setBackgroundResource(imageid);
lyt.addView(ib);
}
所有图像都垂直显示我希望它是水平的
答案 0 :(得分:0)
当可以通过XML完成时,避免在Java代码中设置属性。尝试在orientation
中设置ListView
属性:
<LinearLayout
...
android:orientation="horizontal"
...>
</LinearLayout>
答案 1 :(得分:0)
试试这段代码:
LinearLayout lyt = (LinearLayout) findViewById(R.id.mylayout);
lyt.setOrientation(LinearLayout.HORIZONTAL);
for(i=0;i<=3 ;i++) {
ImageButton ib= new ImageButton(this);
BitmapDrawable imagebd;
ib.setClickable(true);
imageid = getResources().getIdentifier("drawable/" + image,null,getPackageName());
ib.setBackgroundResource(imageid);
lyt.addView(ib);
}
答案 2 :(得分:0)
尝试这样:
LinearLayout lyt = (LinearLayout)findViewById(R.id.mylayout);
LinearLayout buttonsLinearLayout = new LinearLayout(context);
buttonsLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
for(i=0;i<=3 ;i++)
{
ImageButton ib= new ImageButton(this);
BitmapDrawable imagebd;
ib.setClickable(true);
imageid = getResources().getIdentifier("drawable/" + image,null,getPackageName());
ib.setBackgroundResource(imageid);
buttonsLinearLayout.addView(ib);
}
lyt.addView(buttonsLinearLayout);
这样,你仍然有你的主垂直线性布局,所以你可以把东西放在按钮下面。
编辑: 使用它超过1行,我做了一个简单的数学计算......
LinearLayout lyt = (LinearLayout) findViewById(R.id.mylayout);
// calculate the number of rows needed
int numOfButtons = something you already have i guess;
// row layout
LinearLayout buttonsLinearLayout = new LinearLayout(context);
;
for (i = 0; i <= numOfButtons; i++) {
// for every 3 rows, create a new layout
// and add it to the main linear layout
if (i % 3 == 0) {
// create layout for a 3 button row
buttonsLinearLayout = new LinearLayout(context);
buttonsLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
// add the new row with 3 buttons to the main lineal layout
lyt.addView(buttonsLinearLayout);
}
ImageButton ib = new ImageButton(this);
BitmapDrawable imagebd;
ib.setClickable(true);
imageid = getResources().getIdentifier("drawable/" + image, null, getPackageName());
ib.setBackgroundResource(imageid);
buttonsLinearLayout.addView(ib);
}
}
没有经过测试,请告诉我这是否适合您...