本章节翻译自《Beginning-Android-4-Application-Development》,如有翻译不当的地方,敬请指出。

原书购买地址http://www.amazon.com/Beginning-Android-4-Application-Development/dp/1118199545/


除了能从一个Activity返回数据结果之外,向一个Activity传递数据也是很常用的。

1. 新建一个工程,PassData。

2. main.xml中的代码。

[java] view plain copy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical">
  6. <Button
  7. android:id="@+id/btn_SecondActivity"
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content"
  10. android:onClick="onClick"
  11. android:text="ClicktogotoSecondActivity"/>
  12. </LinearLayout>
3. 在res/layout文件夹下,创建secondactivity.xml文件。 [java] view plain copy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical">
  6. <TextView
  7. android:layout_width="fill_parent"
  8. android:layout_height="wrap_content"
  9. android:text="WelcometoSecondActivity"/>
  10. <Button
  11. android:id="@+id/btn_MainActivity"
  12. android:layout_width="fill_parent"
  13. android:layout_height="wrap_content"
  14. android:onClick="onClick"
  15. android:text="Clicktoreturntomainactivity"/>
  16. </LinearLayout>
4. 新建一个Activity子类:SecondActivity.java。 [java] view plain copy
  1. publicclassSecondActivityextendsActivity{
  2. @Override
  3. publicvoidonCreate(BundlesavedInstanceState){
  4. super.onCreate(savedInstanceState);
  5. setContentView(R.layout.secondactivity);
  6. //---getthedatapassedinusinggetStringExtra()---
  7. Toast.makeText(this,getIntent().getStringExtra("str1"),
  8. Toast.LENGTH_SHORT).show();
  9. //---getthedatapassedinusinggetIntExtra()---
  10. Toast.makeText(this,
  11. Integer.toString(getIntent().getIntExtra("age1",0)),
  12. Toast.LENGTH_SHORT).show();
  13. //---gettheBundleobjectpassedin---
  14. Bundlebundle=getIntent().getExtras();
  15. //---getthedatausingthegetString()---
  16. Toast.makeText(this,bundle.getString("str2"),Toast.LENGTH_SHORT)
  17. .show();
  18. //---getthedatausingthegetInt()method---
  19. Toast.makeText(this,Integer.toString(bundle.getInt("age2")),
  20. Toast.LENGTH_SHORT).show();
  21. }
  22. publicvoidonClick(Viewview){
  23. //---useanIntentobjecttoreturndata---
  24. Intenti=newIntent();
  25. //---usetheputExtra()methodtoreturnsome
  26. //value---
  27. i.putExtra("age3",45);
  28. //---usethesetData()methodtoreturnsomevalue---
  29. i.setData(Uri.parse("Somethingpassedbacktomainactivity"));
  30. //---settheresultwithOKandtheIntentobject---
  31. setResult(RESULT_OK,i);
  32. //---destroythecurrentactivity---
  33. finish();
  34. }
  35. }
5. AndroidManifest.xml中的代码。 [java] view plain copy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <manifestxmlns:android="http://schemas.android.com/apk/res/android"
  3. package="net.horsttnann.PassingData"
  4. android:versionCode="1"
  5. android:versionName="1.0">
  6. <uses-sdkandroid:minSdkVersion="10"/>
  7. <application
  8. android:icon="@drawable/ic_launcher"
  9. android:label="@string/app_name">
  10. <activity
  11. android:name=".PassingDataActivity"
  12. android:label="@string/app_name">
  13. <intent-filter>
  14. <actionandroid:name="android.intent.action.MAIN"/>
  15. <categoryandroid:name="android.intent.category.LAUNCHER"/>
  16. </intent-filter>
  17. </activity>
  18. <activity
  19. android:name="net.manoel.PassingData.SecondActivity"
  20. android:label="SecondActivity">
  21. <intent-filter>
  22. <actionandroid:name="net.horsttnann.PassingDataSecondActivity"/>
  23. <categoryandroid:name="android.intent.category.DEFAULT"/>
  24. </intent-filter>
  25. </activity>
  26. </application>
  27. </manifest>

6. PassDataActivity中的代码。

public class PassingDataActivity extends Activity {    /** 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) {    Intent i = new     Intent("net.manoel.PassingDataSecondActivity");    //---use putExtra() to add new key/value pairs---                i.putExtra("str1", "This is a string");    i.putExtra("age1", 25);    //---use a Bundle object to add new key/values     // pairs---      Bundle extras = new Bundle();    extras.putString("str2", "This is another string");    extras.putInt("age2", 35);                    //---attach the Bundle object to the Intent object---    i.putExtras(extras);                    //---start the activity to get a result back---    startActivityForResult(i, 1);    }        public void onActivityResult(int requestCode,     int resultCode, Intent data)    {        //---check if the request code is 1---        if (requestCode == 1) {            //---if the result is OK---             if (resultCode == RESULT_OK) {                //---get the result using getIntExtra()---                Toast.makeText(this, Integer.toString(                    data.getIntExtra("age3", 0)),                     Toast.LENGTH_SHORT).show();                      //---get the result using getData()---                Toast.makeText(this, data.getData().toString(),                     Toast.LENGTH_SHORT).show();            }                    }    }}

7. 按F11调试。


更多相关文章

  1. 没有一行代码,「2020 新冠肺炎记忆」这个项目却登上了 GitHub 中
  2. “罗永浩抖音首秀”销售数据的可视化大屏是怎么做出来的呢?
  3. Nginx系列教程(三)| 一文带你读懂Nginx的负载均衡
  4. 不吹不黑!GitHub 上帮助人们学习编码的 12 个资源,错过血亏...
  5. Android(安卓)用纯代码实现复杂界面
  6. android将path拆分为多个path
  7. android关于AlertDialog加入EditText无法弹出键盘的问题
  8. android 数据库 sqlite数据类型
  9. Android读写文件 (2011-05-15 11:22:22)

随机推荐

  1. android 对象保存到SP
  2. Android布局学习之――按钮居中
  3. Android(安卓)1比1高仿微信图片选择器(新)
  4. Android(安卓)SMS(一) —— 读取短信
  5. android 网络状态判断
  6. webrtc android
  7. CheckBox 设置style 没有效果的原因
  8. Android(安卓)Ethernet以太网使用静态IP
  9. Android(安卓)文件操作
  10. android xml解析