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,定位它们以便它们相互重叠,然后根据需要切换这些LinearLayouts的可见性setVisibility()

于 2012-08-31T22:01:51.640 回答
8

是的,我已经通过以下方式做到了这一点。当我需要设置新的布局(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); 
于 2015-04-13T08:26:13.713 回答
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 回答
1

我会改变整个布局。您只能更改布局的特定部分。

  1. FrameLayout在 中添加一个根your_layout.xml,它不包含任何内容。

    <FrameLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/fl_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    
  2. 在 java 代码中设置您的内容。

    ViewGroup flContent = findViewById(R.id.fl_content);
    
    private void setLayout(int layoutId) {
        flContent.removeAllViews();
        View view = getLayoutInflater().inflate(layoutId, flContent, false);
        flContent.addView(view);
    }
    
  3. 您可以layoutId在某些时候免费更改。
    如果你有一些听众,你必须重新设置。

于 2018-10-29T06:22:38.223 回答