22

特定の条件下で実行時にフラグメントのレイアウトを変更しようとしています。

onCreateView() 内で膨張した初期レイアウト:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.cancel_video, null);
    }

その後、フラグメント コード内で、最初のレイアウトを別のレイアウトに置き換えたいと考えています。

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

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

どうすればこれを達成できますか?

4

4 に答える 4

16

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

于 2012-08-31T22:01:51.640 に答える
5

FragmentManger を介して FragmentTransaction を使用する

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 であるため、ビューを返します

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;
    }   

}
于 2012-08-31T22:02:39.390 に答える