2017-08-20 87 views
0

我想向MainActivity添加一個片段,但是當我爲它添加一個fragmnet時,它覆蓋了主要活動的全部寬度和高度。因此,如何設置片段的寬度和高度以編程方式包裝內容,而不是使用XML。如何以編程方式添加片段的寬度和高度?

這裏是我到目前爲止做的代碼:

MainActivity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:id="@+id/rekl" 
    android:layout_height="match_parent" 
    tools:context="com.example.ankit.fragment2.MainActivity"> 


</RelativeLayout> 

MainActivity.java

+2

設置R.id.rekl上的寬度和高度。 –

+0

顯示您的活動xml –

回答

0

你可以像這樣

FragmentManager m = getFragmentManager(); 
     FragmentTransaction t = m.beginTransaction(); 
     ViewGroup.LayoutParams params = f.getView().getLayoutParams(); 
     params.height = 900; 
     f.getView().setLayoutParams(params); 
     t.add(R.id.frame, f, "Frag"); 
     t.commit(); 
+0

我想指定wrap_content,而不是900.如何做到這一點? – Ankit

+0

_then改變高度像這樣_ params.height = ViewGroup.LayoutParams.WRAP_CONTENT; –

+0

這取決於這個代碼的位置。在活動中的onCreate看起來是最合適的地方,然而在這一點上,片段的視圖還沒有創建,因此'f.getView()'將返回'null',所以這一切都不起作用 – mkilmanas

相關問題