SoFunction
Updated on 2025-04-07

Detailed explanation of the jump instance between Android Activity and Fragment

Jump between Activity and Fragment

Jump directly

Basic usage method

public class MainActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    setContentView(.activity_main);
  }

  public void jump(View view) {
    Intent intent = new Intent(this, );
    ("video_id", "1");
    startActivity(intent);
  }
}

public class VideoPlayActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    setContentView(.activity_video_play);

    Intent intent = getIntent();
  }
}

With the help of tools

But it's useless

public static void startActivity(Context context, Class clazz,Bundle data) {
  Intent intent = new Intent(context, clazz);
  if(data != null){
    (data);
  }
  (intent);
}

Recommended plan

  1. Put new Intent() in the target activity, so that the getIntent in onCreate can form a corresponding
  2. It is easier to understand and manage the situation of one exit and multiple entrances
  3. More convenient to maintain the key and value of the data transmission (that is, the key is defined by the target activity, and the value is the actual source)
public class MainActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    setContentView(.activity_main);
  }

  public void jump(View view) {
    startActivity((this, "1"));
  }

}

public class VideoPlayActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    setContentView(.activity_video_play);

  }

  public static Intent newIntent(Context context, String vid) {
    Intent intent = new Intent(context, );
    ("video_id", vid);
    return intent;
  }
}

Fragment jump

  • First, an empty constructor method is needed, and Fragment recovery and reconstruction must be used.
  • Use newInstance instead of constructor to pass parameters
  • Get the actual parameters in the method
public class MainFragment{

  public MainFragment() {
    // Required empty public constructor
  }

  public static MainFragment newInstance(int pos) {
    MainFragment fragment = new MainFragment();
    Bundle args = new Bundle();
    ("pos", pos);
    (args);
    return fragment;
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    if (getArguments() != null) {
      pos = getArguments().getInt("pos");
    }
  }
}

Thank you for reading, I hope it can help you. Thank you for your support for this site!