Android中activity传值的两种方式
生活随笔
收集整理的這篇文章主要介紹了
Android中activity传值的两种方式
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
第一種:第一個(gè)Activity
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | ?/** ?????*?通過(guò)這個(gè)方法跳轉(zhuǎn)到activity2界面*/ ????public?void?gotoActivity2(View?v){ ????????//創(chuàng)建一個(gè)意圖 ????????Intent?intent=new?Intent(this,MainActivity2.class); ????????? ????????? ????????//第一種傳值方式 ????????Bundle?bundle=new?Bundle(); ????????bundle.putString("name","zhangsan"); ????????bundle.putInt("age",?23); ????????intent.putExtra("person",?bundle); ????????//啟動(dòng)另一個(gè)activity ????????startActivity(intent); ????} |
第二個(gè)Activity
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | /** ?????*?Activity被創(chuàng)建時(shí)調(diào)用 ?????*?可以在該方法中初始化UI組件 ?????*?該方法調(diào)用完畢會(huì)調(diào)用onStart()方法 ?????*?*/ ????@Override ????protected?void?onCreate(Bundle?savedInstanceState)?{ ????????super.onCreate(savedInstanceState); ????????setContentView(R.layout.activity_main2); ????????System.out.println("MainActivity2-onCreate()"); ????????? ????????? ????????//獲取上一個(gè)activity傳過(guò)來(lái)的參數(shù) ????????Intent?intent=getIntent(); ????????Bundle?bundle=intent.getBundleExtra("person"); ????????String?name=?bundle.getString("name"); ????????int?age=bundle.getInt("age"); ????????System.out.println(name+"???:??"+age); ????????TextView?textView=(TextView)?findViewById(R.id.textView2); ????????textView.setText("name="+name+"??age="+age); ????????? ????} |
第二種:activity1
| 1 2 3 | ??????//第二種傳值方式 ????intent.putExtra("name",?"小白"); ???startActivity(intent); |
activity2
| 1 2 3 4 | ??????Intent?intent=getIntent();???????? ??????String?name2=?intent.getStringExtra("name"); ??????TextView?textView=(TextView)?findViewById(R.id.textView2); ??????textView.setText("name2="+name2); |
傳遞自定義類型(自定義類,自定義類必須序列化)
activity1
| 1 2 3 4 | ????????????//傳遞自定義類型 ????????????Cat?cat=new?Cat(1,?"校花",?23); ????????????intent.putExtra("cat",?cat); ????????????startActivity(intent); |
activity2
| 1 2 3 4 5 | ????????????//第二種 ????????????String?name2=?intent.getStringExtra("name"); ????????????Cat?cat=(Cat)?intent.getSerializableExtra("cat"); ????????????TextView?textView=(TextView)?findViewById(R.id.textView2); ????????????textView.setText("cat="+cat.toString()); |
?本文轉(zhuǎn)自 matengbing 51CTO博客,原文鏈接:http://blog.51cto.com/matengbing/1880953
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀
總結(jié)
以上是生活随笔為你收集整理的Android中activity传值的两种方式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: linux中常用的压缩、解压命令详解
- 下一篇: OpenGL ES for Window