2012-08-31 12 views
11

特定の条件でランタイム中にフラグメントのレイアウトを変更しようとしています。フラグメント内に新しいレイアウトを設定する

onCreateView(内で膨張初期レイアウト):次に

​​

いつか後、私はいくつかの他のレイアウトで初期レイアウトを交換したい断片コード内。

私はこれまでにいくつかのことを試みました。これは私が持っている最新のものです:

private void Something(){ 
    if(checkLicenseStatus(licenseStatus, statusMessage)){ 
       View vv = View.inflate(getActivity(), R.layout.play_video, null); 
       //more code 
    } 
} 

どうすればいいですか?

答えて

8

フラグメントのレイアウトが設定されたら置き換えることはできません。条件付きレイアウトが必要な場合は、レイアウトを再設計してより小さなフラグメントに分割するか、すべてのレイアウト要素をサブコンテナ(たとえばLinearLayout)にグループ化してから、RelativeLayoutに配置し、これらの可視性は、必要に応じてsetVisibility()LinearLayoutを表示します。それはビュー

public class YourFragment extends Fragment { 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.your_fragment, container, false); 

     return view; 
    } 

} 
4

がFragmentManger

FragmentManager fm = getFragmentManager(); 

if (fm != null) { 
    // Perform the FragmentTransaction to load in the list tab content. 
    // Using FragmentTransaction#replace will destroy any Fragments 
    // currently inside R.id.fragment_content and add the new Fragment 
    // in its place. 
    FragmentTransaction ft = fm.beginTransaction(); 
    ft.replace(R.id.fragment_content, new YourFragment()); 
    ft.commit(); 
} 

を通じてYourFragmentがちょうどLayoutInflaterあるクラスのコードをFragmentTransactionを使用してはい、私は道を以下でこれを行っています。新しいレイアウト(xml)を設定する必要がある場合、次のコードスニペットを実行する必要があります。

private View mainView; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup containerObject, Bundle savedInstanceState){ 
    super.onCreateView(inflater, containerObject, savedInstanceState); 

     mainView = inflater.inflate(R.layout.mylayout, null); 
     return mainView; 
    } 

    private void setViewLayout(int id){ 
    LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    mainView = inflater.inflate(id, null); 
    ViewGroup rootView = (ViewGroup) getView(); 
    rootView.removeAllViews(); 
    rootView.addView(mainView); 
    } 

私はちょうどこれは、断片全体を交換され、以下の方法

setViewLayout(R.id.new_layout); 
+4

を呼び出し、レイアウトを変更する必要があるとき。私は現在のフラグメントのレイアウトを変更したいだけです。 – Dacto

+0

私も、私はそのための手がかりを持っていません http://stackoverflow.com/questions/28271827/fragment-changing-xml-layout-not-working –

+0

@Dactoフラグメントを置き換える必要があります。変更することはできません'onAttach()'から 'onDetach()'へのフラグメントのレイアウト – surfer190

4

を返すように

+0

'setViewLayout(R.id.new_layout)'しようとすると 'android.view.InflateException'を得る – kamil09875

+0

あなたのコードスニペットと完全なエラーメッセージを見ることはできますか? ? –

+0

これはまさにあなたのコードであり、この例外には何のメッセージもありません。Androidはときどき奇妙です:D BTW。私は断片的にレイアウトを変更するために他の方法を使用した – kamil09875

関連する問題