歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android 使用Intent實現Activity跳轉和數據傳遞

Android 使用Intent實現Activity跳轉和數據傳遞

日期:2017/3/1 10:12:30   编辑:Linux編程
筆記內容:

使用Intent實現Activity之間的跳轉

使用Intent實現Activity跳轉時數據的傳遞

知識重點:

  • 實現跳轉

在編寫一個Android應用時,通常需要在幾個Activity之間實現跳轉。如何實現跳轉,可以使用Intent對象。

在Eclipse中新建一個Android項目,因為需要實現多個Activity跳轉,所以建立兩個文件Android_02.java和Android_02_02.java以及main.xml和main_02.xml兩個界面配置文件。通過點擊第一個界面的按鈕跳轉到第二個界面,首先需要修改main.xml文件。添加如下代碼:

<Button android:id="@+id/button" android:layout_width="fill_parent" android:layout_height="wrap_content"/>

然後在Android_02.java文件中中創建一個按鈕對象。並且為按鈕添加監聽器,當按鈕被按下時執行創建Intent對象並實現跳轉。見如下代碼:

 mybutton.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Intent intent = new Intent(); intent.setClass(Android_02.this, Android_02_02.class);//從前一個Activity跳轉到後一個Activity startActivity(intent); } });

簡單分析下代碼,創建了Intent對象,並且使用對象的setClass(Android_02.this, Android_02_02.class)方法實現跳轉,參數1是當前類名,而第2個參數用來設置跳轉的目的。通過點擊按鈕跳轉到Android_02_02這個Activity。如圖:

第一個Activity

點擊第一個按鈕後轉到了第二個Activity

  • 數據的傳遞

實現在跳轉過程中,從第一個Activity向第二個Activity傳遞數據是很簡單的。首先在按鈕監聽器中創建Intent對象。和跳轉的代碼完全一樣,只不過在其中多一條代碼,通過對象的putExtra("value", "我是傳遞的內容")方法向第二個Activity傳遞數據,第一個參數是傳遞參數的名稱,第二個參數是參數的內容。這樣就向第二個Activity傳遞了一個參數。如下代碼:

 mybutton.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Intent intent = new Intent(); intent.putExtra("value", "我是傳遞的內容");//向Android_02_02傳遞了一個String類型值 intent.setClass(Android_02.this, Android_02_02.class);//從前一個Activity跳轉到後一個Activity startActivity(intent); } });

那麼第二個Activity如何接收這個參數呢。通過

Intent intent = getIntent();

獲得參數內容。並且將參數的內容顯示作為標簽的內容。如下代碼:

Intent intent = getIntent();//得到上一個Activity傳遞的值 String str=intent.getStringExtra("value"); text.setText(str);//將傳遞的值顯示在標簽上

執行如圖:

點擊第一個按鈕後跳轉到第二個Activity且傳遞了參數

Copyright © Linux教程網 All Rights Reserved