利用intent向下一級activity傳遞數(shù)據(jù)
1.png
activity間需要數(shù)據(jù)傳遞的童漩,可以把數(shù)據(jù)從一個activity傳給下一個activity,比如表單的填寫沟蔑,那就需要intent進(jìn)行傳遞。
目的:
單擊按鈕把一字符串當(dāng)前activity向另一個activity傳遞顯示出來狱杰。
步驟:
1瘦材、在FirstActivity中創(chuàng)建按鈕Button5
<Button
android:id="@+id/button_5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/button_5"
android:textAllCaps="false"/>
2、在代碼里給按鈕添加事件監(jiān)聽仿畸。
3食棕、創(chuàng)建Activity名:FourthActivity。
4错沽、FourthActivity中添加文本框控件簿晓。
<TextView
android:id="@+id/textview_1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAlignment="center"
android:textAllCaps="false"
android:textSize="12sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
4、在監(jiān)聽代碼中通過intent 實現(xiàn)啟動FourthActivity并傳遞數(shù)據(jù)千埃。
String data="hell,I sent it.";
intent=new Intent(FirstActivity.this,FourthActivity.class);
intent.putExtra("send_data",data);
5憔儿、FourthActivity接受數(shù)據(jù)
mTv=findViewById(R.id.textview_1);
intent=getIntent();
String data=intent.getStringExtra("send_data");
mTv.setText(data);
要點:
1、putExtra()把數(shù)據(jù)放入Intent放可。
2谒臼、getStringExtra()從Intent取得數(shù)據(jù)朝刊。
3、倆者的鍵值要一樣蜈缤。
4拾氓、getIntent()可獲取傳遞到的Intent。