2012-03-21 96 views
0

我使用FragmentTransaction將片段添加到FrameLayout中。我想動態地改變片段使用的RelativeLayout的邊距。但是,邊距不會隨RelativeLayout.layoutParams而改變。我也用setMargins(),它沒有工作。設置相對佈局的邊距不起作用

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

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

     RelativeLayout infoLayout = (RelativeLayout) view.findViewById(R.id.info); 
     infoLayout.setOnClickListener(new EmptyClickListener()); 

     final int width = 250; 
     final int height = 320; 
     int leftMargin = 0; 
     int topMargin = 0; 
     RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, height); 

     if (x - width < 0) { 
      leftMargin = 0; 
      System.out.println("left " + leftMargin); 
     } 
     else { 
      leftMargin = x - width; 
     } 

     if (y >= 450 && y <= 480) { 
      topMargin = y - height; 
     } 

     params.leftMargin = leftMargin; 
     params.topMargin = topMargin; 

     infoLayout.setLayoutParams(params); 

回答

1

使用嘗試

FrameLayout.LayoutParams 

代替

RelativeLayout.LayoutParams 

佈局預期PARAMS類型爲從父容器,而不是搜索類型,你是將它們設置在

類型
+0

出於某種原因,這可以在運行3.2.1的東芝標籤上運行,但是它不適用於Kindle Fire 2.3.4 – heero 2012-03-21 21:27:06

+0

它拋出任何錯誤?你是否試圖用KF的其他方式(你發佈的方式)來看看它是否倒退? – dymmeh 2012-03-21 21:31:20

+0

它不會引發任何錯誤。我發佈的方式並不適用於點燃火災。 – heero 2012-03-21 21:34:45