Android项目中Fragment与Activity怎么实现相互跳转?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
Activity及Fragment之间的跳转
直接跳转
基本使用方法
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void jump(View view) { Intent intent = new Intent(this, VideoPlayActivity.class); intent.putExtra("video_id", "1"); startActivity(intent); } }
public class VideoPlayActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_video_play); Intent intent = getIntent(); } }
借助工具类
然而并没什么卵用
public static void startActivity(Context context, Class clazz,Bundle data) { Intent intent = new Intent(context, clazz); if(data != null){ intent.putExtras(data); } context.startActivity(intent); }
推荐方案
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void jump(View view) { startActivity(VideoPlayActivity.newIntent(this, "1")); } }
public class VideoPlayActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_video_play); } public static Intent newIntent(Context context, String vid) { Intent intent = new Intent(context, VideoPlayActivity.class); intent.putExtra("video_id", vid); return intent; } }
Fragment跳转
public class MainFragment{ public MainFragment() { // Required empty public constructor } public static MainFragment newInstance(int pos) { MainFragment fragment = new MainFragment(); Bundle args = new Bundle(); args.putInt("pos", pos); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { pos = getArguments().getInt("pos"); } } }
看完上述内容,你们掌握Android项目中Fragment与Activity怎么实现相互跳转的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。