在片段中设置新布局

Dac*_*cto 14 android android-fragments

我试图在特定条件下在运行时更改片段的布局.

在onCreateView()中膨胀的初始布局:

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

然后在片段代码中的某个时间后,我想用其他布局替换初始布局.

到目前为止我已经尝试了一些东西; 这是我的最新消息:

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

我怎么能做到这一点?

Mar*_*ski 12

一旦膨胀,您就无法替换片段的布局.如果您需要条件布局,那么您必须重新设计布局并将其分解为更小的元素Fragments.或者,您可以将所有布局元素分组到子容器(例如LinearLayout)中,然后将它们全部包装RelativeLayout,定位它们以使它们相互叠加,然后根据需要切换这些LinearLayouts 的可见性setVisibility().


Ton*_*thy 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();
}
Run Code Online (Sandbox Code Playgroud)

类YouFragment的代码只是一个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;
    }   

}
Run Code Online (Sandbox Code Playgroud)

  • 这正在取代整个片段.我只想改变当前片段的布局. (4认同)

小智 5

是的,我是按照以下方式做到的.当我需要设置新布局(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);
  }
Run Code Online (Sandbox Code Playgroud)

每当我需要更改布局时,我只需调用以下方法

    setViewLayout(R.id.new_layout); 
Run Code Online (Sandbox Code Playgroud)