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"); } }}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
新闻热点
疑难解答