在Android中交换不同布局的片段,可以使用FragmentManager和FragmentTransaction。以下是一个简单的示例:
public class Fragment1 extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_layout1, container, false);
}
}
public class Fragment2 extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_layout2, container, false);
}
}
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
public class MainActivity extends AppCompatActivity {
private Fragment1 fragment1;
private Fragment2 fragment2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragment1 = new Fragment1();
fragment2 = new Fragment2();
// 默认显示片段1
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, fragment1)
.commit();
}
public void swapFragments(Fragment fragment) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.addToBackStack(null)
.commit();
}
}
// 交换到片段1
swapFragments(fragment1);
// 交换到片段2
swapFragments(fragment2);
这样,就可以在Android中交换不同布局的片段了。
领取专属 10元无门槛券
手把手带您无忧上云