在Android应用中,我们通常需要根据需求选择使用Activity还是Fragment。Activity是应用的界面呈现单元,而Fragment可以看作是Activity中的子视图,也可以独立存在。下面给出在实际开发中使用Activities和Fragments的示例代码。
/* Activity 示例代码 */ public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
/* Fragment 示例代码 */ public class MyFragment extends Fragment { public MyFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_my, container, false); } }
在实际应用开发中,我们需要根据具体的应用场景来选择使用Activity还是Fragment。如果需要展示一个完整的屏幕,通常选择使用Activity来实现;如果需要将屏幕分为不同的部分,每部分可以独立地进行操作,可以考虑使用Fragment。另外,在处理界面跳转和数据共享等方面,Fragment具有比Activity更灵活的优势。因此,在实际应用开发中,我们需要权衡利弊,选择合适的方案。