2014-09-01 82 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爲宗旨

相關問題