2016-12-26 42 views
1

我有一個相對的佈局,其中包含linearLayout與兩個imageView如下。android layout_centerInParent屬性以編程方式添加視圖後不工作

<RelativeLayout 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/rlParent"> 
     <LinearLayout 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:gravity="center" 
      android:orientation="horizontal" 
      android:layout_centerInParent="true"> 

      <ImageView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:id="@+id/imageView" 
       android:layout_marginRight="5dp"/> 

      <ImageView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_marginLeft="5dp"/> 

     </LinearLayout> 

</RelativeLayout> 

,我已添加的自定義編程surfaceView。加入後surfaceViewlinearLayout不在中心顯示。我試圖通過代碼設置layout_centerInParent屬性,但它不起作用。

請幫幫我。

mPreview = new CustomSurfaceView(getActivity(),1, CameraPreview.LayoutMode.FitToParent, false,this); 
    LayoutParams previewLayoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); 

    mLayout.addView(mPreview, 0, previewLayoutParams); 

mLayout是Releativelayout和mPreview是定製surfaceview

+0

你可以添加你的java代碼在哪裏你編程添加surfaceView? –

+0

顯示如何以編程方式添加視圖 –

+0

在LinearLayour或RelativeLayout中添加了'surfaceView'的位置? – FabioR

回答

2

你的父母佈局(這裏RelativeLayout)寬度必須match_parent。那麼只有你的孩子佈局,centerInParent將工作。

+0

如果沒有添加表面視圖線性佈局顯示在中心 – user1767260

+0

感謝它的工作 – user1767260

-2

試試這個android:layout_centerHorizontal="true"代替android:layout_centerInParent="true"

0

嘗試......

<RelativeLayout 
    android:id="@+id/rlParent"> 
    <LinearLayout 
     android:id="@+id/rlChild"> 

     ...... 

    </LinearLayout> 

View mPreview = findViewById(R.id.rlChild); 
RelativeLayout.LayoutParams previewLayoutParams = (RelativeLayout.LayoutParams)mPreview.getLayoutParams(); 
previewLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); 
mPreview.setLayoutParams(previewLayoutParams); 
mLayout.addView(mPreview); 
+0

感謝您的答覆。但它不起作用 – user1767260

+0

RelativeLayout的高度和寬度設置爲「match_parent」 –

0

第二行和第三行,你必須寫match_parent。這就是爲什麼centerinparent不起作用。