2014-09-01 74 views
0

在我的应用程序中,我使用了Fragments(tabs),当我试图设置fragment layout的LinearLayout的边距时,它不起作用。以编程方式在RealtiveLayout中设置页边距margin-of-line

我的布局有这样的RelativeLayout

... 
<RelativeLayout 
    android:id="@+id/calendar_activities" 
    android:layout_width="fill_parent" 
    android:layout_height="match_parent" 
    android:layout_marginLeft="10dp"> 
</RelativeLayout> 
... 

我的片段:

public class FragmentTabSchedule extends Fragment { 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 

     View view = inflater.inflate(R.layout.fragmenttab1, container, false); 

     RelativeLayout rl = (RelativeLayout) view.findViewById(R.id.calendar_activities); 

     LinearLayout ll = new LinearLayout(inflater.getContext()); 
     ll.setOrientation(LinearLayout.VERTICAL); 
     //ll.setPadding(60, 60, 60, 60); 

     Resources r = inflater.getContext().getResources(); 

     int h = (int) TypedValue.applyDimension(
       TypedValue.COMPLEX_UNIT_DIP, 
       60, 
       r.getDisplayMetrics() 
     ); 

     LayoutParams params = new LayoutParams(
       LayoutParams.MATCH_PARENT,  
       h 
     ); 
     params.setMargins(60, 60, 60, 60); 
     ll.setLayoutParams(params); 

     ll.setBackgroundColor(getResources().getColor(R.color.yellow)); 

     TextView act = new TextView(inflater.getContext()); 

     act.setText("Activity test"); 
     ll.addView(act); 

     rl.addView(ll); 



     return view; 
    } 

} 

的LinearLayout中创建正确,只是不工作的事情是保证金(已经尝试过填充没有成功)。布局放置0边距。

当我尝试直接在XML文件中创建的代码,它的工作原理

 <RelativeLayout 
      android:id="@+id/calendar_activities" 
      android:layout_width="fill_parent" 
      android:layout_height="match_parent" 
      android:layout_marginLeft="10dp"> 

      <LinearLayout 
       android:layout_width="fill_parent" 
       android:layout_height="60dp" 
       android:orientation="vertical" 
       android:layout_marginTop="120dp" 
       android:background="@color/blue"> 

       <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="test"/> 

      </LinearLayout> 

     </RelativeLayout> 
+1

而不是使用的LayoutParams的尝试使用RelativeLayout.LayoutParams ...... – maaz 2014-09-01 18:14:32

+0

呀,谢谢@maaz,它的工作 – MiguelDuque 2014-09-01 18:33:24

+0

我已经发布日e回答,请接受它 – maaz 2014-09-01 18:36:31

回答

0

它的工作方式是布局PARAMS一个应该使用应该是从它的父...

在你的情况的LinearLayout里面装的RelativeLayout如此,一个应该使用RelativeLayout.LayoutParams为宗旨

相关问题