search

Home  >  Q&A  >  body text

Android LinearLayout动态添加View时如何设置View间的间距

在一个LinearLayout中动态添加View(Java代码实现):

for (int i = 0; i < mListViews.size(); i++) {
                View v = inflater.inflate(ovalLayoutId, null);
                ovalLayout.addView(v);
            }

其中OvalLayout是一个居中对齐的LinearLayout,ovalLayoutId是要添加的View。如何才能设置这些View之间的间隔(水平方向)?

阿神阿神2773 days ago743

reply all(4)I'll reply

  • 巴扎黑

    巴扎黑2017-04-17 13:37:02

    LinearLayout is vertical:

    androidandroid:layout_marginBottom="Xdip" and/or android:layout_marginTop="Xdip" 
    

    LinearLayout is horizontal:

    androidandroid:layout_marginLeft="Xdip" and/or android:layout_marginRight="Xdip" 
    

    X is a numerical value, such as: 3.

    Hope this helps.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:37:02

    LinearLayout also has a pider, similar to ListView. Set the pider for your ovalLayout, and then set the pider display mode to middle:

    mContainer = new LinearLayout(getContext());
    mContainer.setOrientation(LinearLayout.VERTICAL);
    mContainer.setpiderDrawable(getContext().getResources().getDrawable(R.drawable.common_pider_black_10));
    mContainer.setShowpiders(LinearLayout.SHOW_pIDER_MIDDLE);
    

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:37:02

    There are many ways, just two:
    1. By setting LayoutParams for the view, when adding View, just use layoutParams as an input parameter;
    2. You can add a BlankView with a certain width but a transparent background behind or below the view, so that the views are separated by BlankView.

    reply
    0
  • PHPz

    PHPz2017-04-17 13:37:02

    Add my own Java code writing method:

    for (int i = 0; i < mListViews.size(); i++) {
                    View v = inflater.inflate(ovalLayoutId, null);
                    if(i==0){
                        ovalLayout.addView(v);//第一个view不用设置间隔
                    }
                    else {
                        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT);
                        lp.setMargins(15,0,0,0);
                        v.setLayoutParams(lp);
                        ovalLayout.addView(v);
                    }
    
                }
    

    reply
    0
  • Cancelreply