Android 程式開發:(二)使用意圖 —— 2.4 使用Intent傳遞資料

來源:互聯網
上載者:User

除了能從一個Activity返回資料結果之外,向一個Activity傳遞資料也是很常用的。
    1.建立一個名為PassData的工程。
 
    2.main.xml中的代碼。
 
[java] view plaincopy<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 
 
    <Button 
        android:id="@+id/btn_SecondActivity" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:onClick="onClick" 
        android:text="Click to go to Second Activity" /> 
 
</LinearLayout> 
    3.在res/layout檔案夾下,建立secondactivity.xml檔案。[java] view plaincopy<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 
 
    <TextView 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="Welcome to Second Activity" /> 
 
    <Button 
        android:id="@+id/btn_MainActivity" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:onClick="onClick" 
        android:text="Click to return to main activity" /> 
 
</LinearLayout> 
    4.建立一個Activity子類:SecondActivity.java。[java] view plaincopypublic class SecondActivity extends Activity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.secondactivity); 
 
        // ---get the data passed in using getStringExtra()--- 
        Toast.makeText(this, getIntent().getStringExtra("str1"), 
                Toast.LENGTH_SHORT).show(); 
 
        // ---get the data passed in using getIntExtra()--- 
        Toast.makeText(this, 
                Integer.toString(getIntent().getIntExtra("age1", 0)), 
                Toast.LENGTH_SHORT).show(); 
 
        // ---get the Bundle object passed in--- 
        Bundle bundle = getIntent().getExtras(); 
 
        // ---get the data using the getString()--- 
        Toast.makeText(this, bundle.getString("str2"), Toast.LENGTH_SHORT) 
                .show(); 
 
        // ---get the data using the getInt() method--- 
        Toast.makeText(this, Integer.toString(bundle.getInt("age2")), 
                Toast.LENGTH_SHORT).show(); 
    } 
 
    public void onClick(View view) { 
        // ---use an Intent object to return data--- 
        Intent i = new Intent(); 
 
        // ---use the putExtra() method to return some 
        // value--- 
        i.putExtra("age3", 45); 
 
        // ---use the setData() method to return some value--- 
        i.setData(Uri.parse("Something passed back to main activity")); 
  
        // ---set the result with OK and the Intent object--- 
        setResult(RESULT_OK, i); 
 
        // ---destroy the current activity--- 
        finish(); 
    } 

    5.AndroidManifest.xml中的代碼。[java] view plaincopy<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="net.horsttnann.PassingData" 
    android:versionCode="1" 
    android:versionName="1.0" > 
 
    <uses-sdk android:minSdkVersion="10" /> 
 
    <application 
        android:icon="@drawable/ic_launcher" 
        android:label="@string/app_name" > 
        <activity 
            android:name=".PassingDataActivity" 
            android:label="@string/app_name" > 
            <intent-filter> 
                <action android:name="android.intent.action.MAIN" /> 
 
                <category android:name="android.intent.category.LAUNCHER" /> 
            </intent-filter> 
        </activity> 
        <activity 
            android:name="net.horsttnann.PassingData.SecondActivity" 
            android:label="Second Activity" > 
            <intent-filter> 
                <action android:name="net.horsttnann.PassingDataSecondActivity" /> 
 
                <category android:name="android.intent.category.DEFAULT" /> 
            </intent-filter> 
        </activity> 
    </application> 
 
</manifest> 
 
    6.PassDataActivity中的代碼。
 
 
[java] view plaincopyprint?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.learn2develop.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(); 
            }             
        } 
    } 
 

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.learn2develop.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調試。
 
 
 
 

 
    程式第一次啟動:
 



    跳轉到SecondActivity:

    返回PassDataActivity:


 作者 manoel的專欄

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.