代码之家  ›  专栏  ›  技术社区  ›  MiguelDuque

以编程方式设置RealiveLayout中LinearLayout的边距-不起作用

  •  0
  • MiguelDuque  · 技术社区  · 10 年前

    在我的应用程序中,我使用片段(选项卡),当我尝试设置片段布局的LinearLayout的边距时,它不起作用。

    我的布局具有此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 回复  |  直到 10 年前
        1
  •  1
  •   maaz    10 年前

    它的工作方式是Layout参数,应该使用的参数应该来自其父项。。。

    在您的案例中,LinearLayout位于RelativeLayout内部,因此,应该使用RelativeLlayout.LayoutParams