一、代码
1.xml
(1)activity_main.xml
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:paddingBottom="@dimen/activity_vertical_margin" 6 android:paddingLeft="@dimen/activity_horizontal_margin" 7 android:paddingRight="@dimen/activity_horizontal_margin" 8 android:paddingTop="@dimen/activity_vertical_margin" 9 tools:context="com.parcel.MainActivity" > 10 11 <Button 12 android:id="@+id/saveDataBtn" 13 android:layout_width="wrap_content" 14 android:layout_height="wrap_content" 15 android:text="放数据" /> 16 <Button 17 android:id="@+id/getDataBtn" 18 android:layout_width="wrap_content" 19 android:layout_height="wrap_content" 20 android:text="取数据" 21 android:layout_below="@id/saveDataBtn"/> 22 23 </RelativeLayout>
(2)AndroidManifest.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android" 3 package="com.parcel" 4 android:versionCode="1" 5 android:versionName="1.0" > 6 7 <uses-sdk 8 android:minSdkVersion="8" 9 android:targetSdkVersion="21" /> 10 11 <application 12 android:allowBackup="true" 13 android:icon="@drawable/ic_launcher" 14 android:label="@string/app_name" 15 android:theme="@style/AppTheme" > 16 <activity 17 android:name=".MainActivity" 18 android:label="@string/app_name" > 19 <intent-filter> 20 <action android:name="android.intent.action.MAIN" /> 21 22 <category android:name="android.intent.category.LAUNCHER" /> 23 </intent-filter> 24 </activity> 25 </application> 26 27 </manifest>
2.java
(1)MainActivity.java
1 package com.parcel; 2 3 import android.app.Activity; 4 import android.os.Bundle; 5 import android.os.Parcel; 6 import android.view.View; 7 import android.view.View.OnClickListener; 8 import android.widget.Button; 9 10 public class MainActivity extends Activity { 11 12 private Button getDataBtn,saveDataBtn; 13 private Parcel parcel = null; 14 @Override 15 protected void onCreate(Bundle savedInstanceState) { 16 super.onCreate(savedInstanceState); 17 setContentView(R.layout.activity_main); 18 parcel = Parcel.obtain(); 19 saveDataBtn = (Button) findViewById(R.id.saveDataBtn); 20 getDataBtn = (Button) findViewById(R.id.getDataBtn); 21 saveDataBtn.setOnClickListener(new OnClickListener() { 22 @Override 23 public void onClick(View v) { 24 parcel.writeString("testparcel"); 25 parcel.writeInt(666); 26 parcel.writeFloat(0.999F); 27 } 28 }); 29 30 getDataBtn.setOnClickListener(new OnClickListener() { 31 @Override 32 public void onClick(View v) { 33 parcel.setDataPosition(0);//把指针移到最前面 34 String str = parcel.readString(); 35 int i = parcel.readInt(); 36 float f= parcel.readFloat(); 37 System.out.println(str); 38 System.out.println(i); 39 System.out.println(f); 40 } 41 }); 42 } 43 }
时间: 2024-10-14 15:44:17