Android 程式开发:(二)使用意图 —— 2.3 从Intent返回结果
startActivity()方法可以调用另外的Activity,但这种方法不会给当前的Activity返回一个结果。例如,你有一个Activity提示用户输入用户名和密码,用户输入的信息需要被“回传”给这个输入信息的Activity,那就需要使用startActivityForResult()方法。1.secondactivity.xml中的代码。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is the Second Activity!" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Please enter your name" />
<EditText
android:id="@+id/txt_username"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn_OK"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="OK" />
</LinearLayout>
2.SecondActivity.java中的代码。package net.horsttnann.UsingIntent;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class SecondActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
}
public void onClick(View view) {
Intent data = new Intent();
// ---get the EditText view---
EditText txt_username = (EditText) findViewById(R.id.txt_username);
// ---set the data to pass back---
data.setData(Uri.parse(txt_username.getText().toString()));
setResult(RESULT_OK, data);
// ---closes the activity---
finish();
}
}
3.UsingIntentActivity.java中的代码。package net.horsttnann.UsingIntent;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class UsingIntentActivity extends Activity {
int request_Code = 1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClick(View view) {
// startActivity(new Intent("net.horsttnann.SecondActivity"));
// or
// startActivity(new Intent(this, SecondActivity.class));
startActivityForResult(new Intent("net.horsttnann.SecondActivity"),
request_Code);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == request_Code) {
if (resultCode == RESULT_OK) {
Toast.makeText(this, data.getData().toString(),
Toast.LENGTH_SHORT).show();
}
}
}
}
4.按F11调试。
效果图:
程序第一次被加载:
点击按钮,使用startActivityForResult()方法调用SecondActivity:
点击OK按钮,返回到UsingIntentActivity:
www.zzzyk.com
作者 manoel的专栏
补充:移动开发 , Android ,