通过代码为视图设置android:layout_margin

时间:2013-01-30 06:33:15

标签: android android-view

在我的应用程序中,我正在创建一个LinearLayout。当我向布局添加其他视图时,它们显得太近(两个视图之间的差异非常窄)。我想为布局中添加的视图设置android:layout_margin。这怎么可能?

3 个答案:

答案 0 :(得分:1)

试试这个

LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
     LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

params.setMargins(10, 20, 30, 40);

Button button = new Button(this);
button.setText("some text");
layout.addView(button, params);

答案 1 :(得分:0)

如果您尝试通过xml执行此操作,请执行此操作

android:layout_marginLeft="10dp"   //example
android:layout_marginRight="10dp" 
android:layout_marginTop="10dp" 
android:layout_marginBottom="10dp" 

您希望在左侧,右侧,顶部或底部设置边距

答案 2 :(得分:0)

试试这个

 RelativeLayout.LayoutParams  my_params;             
 my_params= new RelativeLayout.LayoutParams(12,12);    
 my_params.leftMargin =57;    
 my_params.topMargin =143;     
 rl_main.addView(mProgress,my_params);  

此处 rl_main 是主要布局       并且 mprogress 是添加的对象。