Android 数据传递-通过静态变量传递数据

使用Intent可以很方便在不同的Activity之间传递数据,这个也是官方推荐的方式,但是也有一定的局限性,就是Intent无法传递不能序列化的对象,例如(图片)。我们可以使用静态变量来解决这个问题
 
Ø案例一
package com.android.myintent;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Main extends Activity {
	/** Called when the activity is first created. */
	private Button button;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		button = (Button) this.findViewById(R.id.button);
		button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// 声明一个意图
				Intent intent = new Intent();
				intent.setClass(Main.this, OtherActivity.class);
				OtherActivity.age = 23;
				OtherActivity.name = "jack";
				startActivity(intent);
			}
		});
	}
}
package com.android.myintent;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class OtherActivity extends Activity {

	private TextView textView;
	public static String name;
	public static int age;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.other);
		textView = (TextView)this.findViewById(R.id.msg);
		textView.setText("-name->>"+name+"\n"+"-age-->>"+age);
	}
}

相关推荐