我正在尝试在特定条件下在运行时更改片段的布局。
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
}
}
我该如何做到这一点?
答案 0 :(得分:12)
充气后,您无法替换片段的布局。如果您需要条件布局,那么您必须重新设计布局并将其分解为更小的元素,如Fragments
。或者,您可以将所有布局元素分组到子容器中(例如LinearLayout
),然后将它们全部包装在RelativeLayout
中,将它们放置在一起,使它们相互叠加,然后切换这些LinearLayout
的可见性s根据需要setVisibility()
。
答案 1 :(得分: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;
}
}
答案 2 :(得分: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);
}
每当我需要更改布局时,我只需调用以下方法
setViewLayout(R.id.new_layout);
答案 3 :(得分:0)
我将更改整个布局。您只能更改布局的特定部分。
在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" />
在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);
}
您可以随时免费更改layoutId
。
如果您有一些侦听器,则必须重新设置。