你的位置:首页 > 操作系统

[操作系统]我的android学习经历15


利用Intent实现有返回结果的页面跳转

主要用的方法:

(1)Intent的构造方法:intent(当前界面对象,要跳转的界面.class);

(2)接受结果的方法onActivityResult(int requestCode, int resultCode, Intent data) 

(3)调用开始的方法 startActivityForResult(Intent intent ,int requestCode );

(4)setResult( int resultCode, Intent in);   //在跳转后的界面中写

(5)in.putExtra("返回", "已返回回转结果"); //与(4)结合使用,存放结果键值对

代码如下:第一个页面

package com.example.intentexample;

import javax.security.auth.PrivateCredentialPermission;

import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager.OnActivityResultListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

private Button bt;
private TextView tv;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt=(Button) findViewById(R.id.button1);
tv=(TextView) findViewById(R.id.textView2);
bt.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent=new Intent(MainActivity.this,FActivity.class);
startActivityForResult(intent, 1);
}
});
}
@Override
protected void onActivityResult(int arg0, int arg1, Intent arg2) {
// TODO Auto-generated method stub
super.onActivityResult(arg0, arg1, arg2);
if(arg0==1&&arg1==2){
tv.setText(arg2.getStringExtra("返回"));
}
}

}

 

第二个界面

package com.example.intentexample;

import javax.security.auth.PrivateCredentialPermission;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class FActivity extends Activity{
private Button bt;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.factivity);
bt=(Button) findViewById(R.id.button1);
bt.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent in=new Intent();
in.putExtra("返回", "已返回回转结果");
setResult(2, in);
finish();
}
});
}
}

 

界面跳转前为

界面跳转后为:

页面返回结果后为: