利用Intent實現有返回結果的頁面跳轉 主要用的方法: (1)Intent的構造方法:intent(當前界面對象,要跳轉的界面.class); (2)接受結果的方法onActivityResult(int requestCode, int resultCode, Intent data) (3)調 ...
利用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();
}
});
}
}
界面跳轉前為
界面跳轉後為:
頁面返回結果後為: