android学习之路--------intent

时间:2023-10-25 16:14:44

正式开始学习android,没有看书和视频,所以没有系统的学,只是看到哪个知识点就去学习,今天学习界面之间的跳转,以及传值,主要的知识点是intent,

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
LinearLayout view = new LinearLayout(getApplicationContext());
setContentView(view);
setTitle("这是一个activity");
Button button = new Button(getApplicationContext());
button.setText("点击我跳转到下一个界面");
view.addView(button);
button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setClass(getApplicationContext(), ActivityTest1.class);
intent.putExtra("key", "11");
startActivityForResult(intent, 1);
}
});
}

setClass表示要跳转到哪个页面去,putExtra 表示要传给下个界面的值,类似key,value的方法。

startActivity( )仅仅是跳转到目标页面,若是想跳回当前页面,则必须再使用一次startActivity( );

可以一次性完成这项任务,当程序执行到这段代码的时候,假若从T1Activity跳转到下一个Text2Activity,而当这个Text2Activity调用了finish()方法以后,程序会自动跳转回T1Activity,并调用前一个T1Activity中的onActivityResult( )方法。

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println(requestCode+"::::requestCode");
System.out.println(resultCode+"::::resultCode");
if(requestCode == resultCode){
Bundle bundle = data.getExtras();
String param = bundle.getString("active1");
setTitle(param);
}
}

另外一个界面

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.second_activity);
LinearLayout view = new LinearLayout(getApplicationContext());
setContentView(view);
Bundle bundle = getIntent().getExtras();
if(bundle != null){
setTitle("主界面"+bundle.getString("key"));
}
Button button = new Button(getApplicationContext());
button.setText("点击我跳转到上个界面");
view.addView(button);
button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
Bundle bundle = new Bundle();
bundle.putString("active1", "这个是activity1传过来的数据");
Intent intent = new Intent();
intent.putExtras(bundle);
setResult(1,intent);
finish();
}
});
}