Activity及Fragment之间的跳转

2016-05-09  本文已影响1246人  小范屯

##直接跳转

基本使用方法

```java

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

}

}

```

##借助工具类

然而并没什么卵用

```java

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是实际的来源)

```java

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跳转

1. 首先需要一个空的构造方法,Fragment恢复重建要使用。

2. 使用newInstance代替构造方法传参

3. 在Fragment.onCreate方法获取实参

```java

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

}

}

}

```

上一篇下一篇

猜你喜欢

热点阅读