3.11 返回数据到前一个Activity

《Google Android SDK开发范例大全》第3章为大家讲述的是用户人机界面,本节为大家介绍返回数据到前一个Activity。

AD: 51CTO云计算架构师峰会 抢票进行中!

 

3.11 返回数据到前一个Activity

startActivityForResult方法

范例说明

上一个范例中,好不容易将数据从Activity1传递至Activity2,如果要再回到Activity1,数据该不会要再封装一次吧?而且前一个Activity1早就被程序destroy了,倘若在Activity1最后以finish() 结束程序,再通过Activity2将数据采用Bundle的方式通过新打开Activity1传递参数,这样的做法虽然也可以恢复User输入的数据,但是并不符合我们的期待,尤其是User曾经输入过的数据,如果不小心点击回到上一页,数据就消失不见,这就不妙了。

有鉴于科技始终来自于人性,如果要在次页面加上一个"回上页"的按钮,而非通过模拟器的回复键,且回上页后又能保留之前输入的相关信息,那么就必须使用startActivityForResult()来唤起一个Activity。利用这个方法,前一个Activity1便会有一个等待次Activity2的返回,而返回的数据就可以达到我们想要的结果。

运行结果

 

范例程序

  1. src/irdc.ex03_11/EX03_11.java 

在Activity1主程序中调用Activity的方法更改成startActivityForResult(intent,0),其中0为下一个Activity要返回值的依据,可指定为自行定义的参考标识符(Identifier)。程序覆盖了onActivityResult() 这个方法,令程序在收到result后,再重新加载写回原本输入的值。

 

  1. package irdc.ex03_11;  
  2.  
  3. /* import相关class */ 
  4. import android.app.Activity;  
  5. import android.content.Intent;  
  6. import android.os.Bundle;  
  7. import android.view.View;  
  8. import android.widget.Button;  
  9. import android.widget.EditText;  
  10. import android.widget.RadioButton;  
  11.  
  12. public class EX03_11 extends Activity   
  13. {  
  14.   private EditText et;  
  15.   private RadioButton rb1;  
  16.   private RadioButton rb2;  
  17.       
  18.   /** Called when the activity is first created. */ 
  19.   @Override 
  20.   public void onCreate(Bundle savedInstanceState)   
  21.   {  
  22.     super.onCreate(savedInstanceState);  
  23.     /* 载入main.xml Layout */ 
  24.     setContentView(R.layout.main);  
  25.       
  26.     /* 以findViewById()取得Button对象,并添加onClickListener */ 
  27.     Button b1 = (Button) findViewById(R.id.button1);  
  28.     b1.setOnClickListener(new Button.OnClickListener()  
  29.     {  
  30.       public void onClick(View v)  
  31.       {  
  32.         /*取得输入的身高*/ 
  33.         et = (EditText) findViewById(R.id.height);  
  34.         double height=Double.parseDouble(et.getText().toString());  
  35.         /*取得选择的性别*/ 
  36.         String sex="";  
  37.         rb1 = (RadioButton) findViewById(R.id.sex1);  
  38.         rb2 = (RadioButton) findViewById(R.id.sex2);  
  39.         if(rb1.isChecked())  
  40.         {  
  41.           sex="M";  
  42.         }  
  43.         else 
  44.         {  
  45.           sex="F";  
  46.         }      
  47.           
  48.         /*new一个Intent对象,并指定class*/ 
  49.         Intent intent = new Intent();  
  50.         intent.setClass(EX03_11.this,EX03_11_1.class);  
  51.           
  52.         /*new一个Bundle对象,并将要传递的数据传入*/ 
  53.         Bundle bundle = new Bundle();  
  54.         bundle.putDouble("height",height);  
  55.         bundle.putString("sex",sex);  
  56.         
  57.         /*将Bundle对象assign给Intent*/ 
  58.         intent.putExtras(bundle);  
  59.         
  60.         /*调用Activity EX03_11_1*/ 
  61.         startActivityForResult(intent,0);  
  62.       }  
  63.     });  
  64.   }  
  65.     
  66.   /* 覆盖 onActivityResult()*/ 
  67.   @Override 
  68.   protected void onActivityResult(int requestCode, int resultCode,  
  69.                                   Intent data)  
  70.   {  
  71.     switch (resultCode)  
  72.     {   
  73.       case RESULT_OK:  
  74.         /* 取得来自Activity2的数据,并显示于画面上 */    
  75.         Bundle bunde = data.getExtras();  
  76.         String sex = bunde.getString("sex");  
  77.         double height = bunde.getDouble("height");  
  78.           
  79.         et.setText(""+height);  
  80.         if(sex.equals("M"))  
  81.         {  
  82.           rb1.setChecked(true);  
  83.         }  
  84.         else 
  85.         {  
  86.           rb2.setChecked(true);  
  87.         }  
  88.         break;  
  89.       default:  
  90.         break;  
  91.      }   
  92.    }   

src/irdc.ex03_11/EX03_11_1.java

在Activity2的主程序中,设计当Button被点击时,将Bundle对象与结果返回给前一个Activity1。

  1. package irdc.ex03_11;  
  2.  
  3. /* import相关class */ 
  4. import java.text.DecimalFormat;  
  5. import java.text.NumberFormat;  
  6. import android.app.Activity;  
  7. import android.content.Intent;  
  8. import android.os.Bundle;  
  9. import android.view.View;  
  10. import android.widget.Button;  
  11. import android.widget.TextView;  
  12.  
  13. public class EX03_11_1 extends Activity   
  14. {  
  15.   Bundle bunde;  
  16.   Intent intent;  
  17.   /** Called when the activity is first created. */ 
  18.   @Override 
  19.   public void onCreate(Bundle savedInstanceState)   
  20.   {  
  21.     super.onCreate(savedInstanceState);  
  22.     /* 载入mylayout.xml Layout */ 
  23.     setContentView(R.layout.myalyout);  
  24.       
  25.     /* 取得Intent中的Bundle对象 */ 
  26.     intent=this.getIntent();  
  27.     bunde = intent.getExtras();  
  28.       
  29.     /* 取得Bundle对象中的数据 */ 
  30.     String sex = bunde.getString("sex");  
  31.     double height = bunde.getDouble("height");  
  32.       
  33.     /* 判断性别 */ 
  34.     String sexText="";  
  35.     if(sex.equals("M"))  
  36.     {  
  37.       sexText="男性";  
  38.     }  
  39.     else 
  40.     {  
  41.       sexText="女性";  
  42.     }  
  43.       
  44.     /* 取得标准体重 */ 
  45.     String weight=this.getWeight(sex, height);  
  46.       
  47.     /* 设置输出文字 */ 
  48.     TextView tv1=(TextView) findViewById(R.id.text1);  
  49.     tv1.setText("你是一位"+sexText+"\n你的身高是"+height+  
  50.                    "厘米\n你的标准体重是"+weight+"公斤");  
  51.       
  52.     /* 以findViewById()取得Button对象,并添加onClickListener */ 
  53.     Button b1 = (Button) findViewById(R.id.button1);  
  54.     b1.setOnClickListener(new Button.OnClickListener()  
  55.     {  
  56.       public void onClick(View v)  
  57.       {            
  58.         /* 返回result回上一个activity */ 
  59.         EX03_11_1.this.setResult(RESULT_OK, intent);  
  60.           
  61.         /* 结束这个activity */ 
  62.         EX03_11_1.this.finish();  
  63.       }  
  64.     });  
  65.   }  
  66.     
  67.   /* 四舍五入的method */ 
  68.   private String format(double num)  
  69.   {  
  70.     NumberFormat formatter = new DecimalFormat("0.00");  
  71.     String s=formatter.format(num);  
  72.     return s;  
  73.   }  
  74.  
  75.   /* 以findViewById()取得Button对象,并添加onClickListener */    
  76.   private String getWeight(String sex,double height)  
  77.   {  
  78.     String weight="";  
  79.     if(sex.equals("M"))  
  80.     {  
  81.       weight=format((height-80)*0.7);  
  82.     }  
  83.     else 
  84.     {  
  85.       weight=format((height-70)*0.6);  
  86.     }    
  87.     return weight;  
  88.   }  

res/layout/mylayout.xml

mylayout.xml为Activity2(EX03_11_1)的Layout,其中定义了显示计算结果的TextView与回上一页的Button按钮。

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <AbsoluteLayout  
  3.   android:layout_width="fill_parent" 
  4.   android:layout_height="fill_parent" 
  5.   xmlns:android="http://schemas.android.com/apk/res/android" 
  6. >  
  7.   <TextView  
  8.     android:id="@+id/text1" 
  9.     android:layout_width="wrap_content" 
  10.     android:layout_height="wrap_content" 
  11.     android:textSize="20sp" 
  12.     android:layout_x="50px" 
  13.     android:layout_y="72px" 
  14.   >  
  15.   </TextView>  
  16.   <Button  
  17.     android:id="@+id/button1" 
  18.     android:layout_width="100px" 
  19.     android:layout_height="48px" 
  20.     android:text="回上一页" 
  21.     android:layout_x="110px" 
  22.     android:layout_y="180px" 
  23.   >  
  24.   </Button>  
  25. </AbsoluteLayout> 

AndroidManifest.xml

范例中有两个Activity,所以AndroidManifest.xml里必须有这两个activity的声明,否则系统将无法运行。

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest  
  3.   xmlns:android="http://schemas.android.com/apk/res/android" 
  4.   package="irdc.ex03_11" 
  5.   android:versionCode="1" 
  6.   android:versionName="1.0.0">  
  7.   <application  
  8.     android:icon="@drawable/icon"   
  9.     android:label="@string/app_name">  
  10.     <activity  
  11.       android:name=".EX03_11" 
  12.       android:label="@string/app_name">  
  13.       <intent-filter>  
  14.         <action android:name="android.intent.action.MAIN" />  
  15.         <category android:name="android.intent.category.LAUNCHER" />  
  16.       </intent-filter>  
  17.     </activity>  
  18.     <activity android:name="EX03_11_1"></activity>  
  19.   </application>  
  20. </manifest> 

扩展学习

范例中为了在回到上一页时,能够显示之前所输入的数据,故将原本传递次Activity的Intent(里面包含了有数据的Bundle对象)再重新返回给主Activity1。如果要在次Activity2中返回其它的数据,例如,经过计算后的结果、数据,此时只需将要返回的数据再放入Bundle对象中即可达成。

此外,以本范例而言,其实使用startActivity()也可达成同样的结果,仅需在主Activity被create时去判断Intent内有没有数据,有的话,就将数据带入;没有的话,就带入空值(null)。但程序还需要再做有无值的比较,较为繁琐,既然Android API中有提供更好用的方法,何来不用的道理?更何况如果系统不是只有几行代码,而是几十行、几百行代码,那时头可就大了!

posted on 2012-08-09 12:47  Code大蛇丸  阅读(231)  评论(0编辑  收藏  举报