Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> Android中Intent在Activity之間傳遞對象[Serializable或Parcelable]

Android中Intent在Activity之間傳遞對象[Serializable或Parcelable]

編輯:關於android開發

Android中Intent在Activity之間傳遞對象[Serializable或Parcelable]


使用intent啟動activity

  /** 
     * Serializeable傳遞對象的方法 
     */  
    private void SerializeMethod(){  
        Person mPerson = new Person();     
        mPerson.setName("andy");     
        mPerson.setAge(26);     
        Intent mIntent = new Intent(this,SerializableDemo.class);     
        Bundle mBundle = new Bundle();     
        mBundle.putSerializable(SER_KEY,mPerson);     
        mIntent.putExtras(mBundle);     

        startActivity(mIntent);     
    }  

    /** 
     * Pacelable傳遞對象方法  
     */  
    private void PacelableMethod(){  
        Police mPolice = new Police();     
        mPolice.setName("I am Police");        
        mPolice.setWorkTime(2008);     
        Intent mIntent = new Intent(this,ParcelableDemo.class);     
        Bundle mBundle = new Bundle();     
        mBundle.putParcelable(PAR_KEY, mPolice);     
        mIntent.putExtras(mBundle);     

        startActivity(mIntent);     
    }  

接收

public class SerializableDemo extends Activity {  

    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  

        TextView mTextView = new TextView(this);     
        Person mPerson = (Person)getIntent().getSerializableExtra(TestActivity.SER_KEY);     
        mTextView.setText("You name is: " + mPerson.getName() + "/n"+     
                          "You age is: " + mPerson.getAge());     

        setContentView(mTextView);     
    }  

}  
public class ParcelableDemo extends Activity {  

    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  

        TextView mTextView = new TextView(this);     
        Police mPolice = (Police)getIntent().getParcelableExtra(TestActivity.PAR_KEY);     
        mTextView.setText("Police name is: " + mPolice.getName()+"/n"+     
                          "WorkTime is: " + mPolice.getWorkTime() + "/n");     
        setContentView(mTextView);     
    }  

}  

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved