在Android中,可以使用FragmentTransaction类和FragmentManager类来实现导航和移动未连接的片段。
以下是一个示例代码,说明如何在Android中进行导航并移动未连接的片段:
public class MainActivity extends AppCompatActivity {
private FragmentManager fragmentManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getSupportFragmentManager();
}
public void navigateToFragmentA(View view) {
FragmentA fragmentA = new FragmentA();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.fragment_container, fragmentA);
transaction.addToBackStack(null);
transaction.commit();
}
public void navigateToFragmentB(View view) {
FragmentB fragmentB = new FragmentB();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.fragment_container, fragmentB);
transaction.addToBackStack(null);
transaction.commit();
}
}
public class FragmentA extends Fragment {
// FragmentA的布局文件为fragment_a.xml
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_a, container, false);
}
}
public class FragmentB extends Fragment {
// FragmentB的布局文件为fragment_b.xml
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_b, container, false);
}
}
这样,当点击按钮时,即可导航到相应的片段,并将其显示在片段容器中。通过使用addToBackStack(null)方法,可以将每个导航的片段添加到返回堆栈,以便在按下返回按钮时,返回到上一个片段。