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);
}
}
ユーティリティクラス
しかし卵の役に立たない
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");
}
}
}