Android Activity与Fragment之间的跳转实例详解

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);
}

推荐方案

  1. 把new Intent()放在目标Activity,这样可以onCreate里的getIntent形成对应
  2. 更容易理解和管理一个出口,多个入口的情况
  3. 较方便维护传递数据的key和value(即key由目标Activity来定义,value是实际的来源)
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跳转

  • 首先需要一个空的构造方法,Fragment恢复重建要使用。
  • 使用newInstance代替构造方法传参
  • 在Fragment.onCreate方法获取实参
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");
    }
  }
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!