亲宝软件园·资讯

展开

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

人气:0
想了解Android Activity与Fragment之间的跳转实例详解的相关内容吗,在本文为您仔细讲解Android Activity与Fragment 跳转的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Android,Activity与Fragment之间的跳转,Activity与Fragment跳转,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跳转

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

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

加载全部内容

相关教程
猜你喜欢
用户评论