2012-05-22 93 views
4

我想更改寬度在主Activity中的一個片段?是可能的,因爲我沒有找到一個 「的LayoutParams」 與更改默認:動態調整大小片段android

public class MainActivity extends Activity { 
/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 


    int widthFfragment=300; 



    Display display = getWindowManager().getDefaultDisplay(); 
    Point size = new Point(); 
    display.getSize(size); 
    widthTot = size.x; 
    heightTot = size.y; 



    findViewById(R.id.f1).getLayoutParams().width = widthTot-widthFfragment; 

}}

這是片段代碼:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/f1" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:background="#330000" 
android:gravity="center_horizontal|center_vertical" 
android:orientation="vertical" > 

<TextView 
    android:id="@+id/textView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Fragment 1" 
    android:textAppearance="?android:attr/textAppearanceLarge" /> 

片段1。 java

public class Fragment1 extends Fragment{ 
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 


    //---Inflate the layout for this fragment--- 
    return inflater.inflate(R.layout.fragment1, container, false); 
} 

}

感謝

回答

4

您的權利,該片段不具備的LayoutParams因爲它是一個概念上的容器,你要麼需要調整充氣視圖的佈局PARAMS的片段,或在容器您將片段。

public class Fragment1 extends Fragment{ 
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

    ViewGroup view = (ViewGroup) inflater.inflate(R.layout.fragment1, container, false); 

    // TODO Adjust layout params of inflated view here 

    return view; 
} 

該示例假定您正在充氣ViewGroup。

希望有所幫助。

+0

謝謝,我需要調整的主要活動,這可能嗎? – bill23

+0

我用LayoutParams解決它並設置適當的大小。非常感謝 – bill23

9

您可以通過使用從Fragment.getView()獲得的View的LayoutParams實例進行操作。我的示例代碼:

private void resizeFragment(Fragment f, int newWidth, int newHeight) { 
    if (f != null) { 
     View view = f.getView(); 
     RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(newWidth, newHeight); 
     view.setLayoutParams(p); 
     view.requestLayout();  


    } 
} 

,並且可以使用如下:

resizeFragment(myFragment, 200, 500); 
resizeFragment(otherFragment, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);