Android 全局变量 Application

  • Post author:
  • Post category:其他



MainActivity

public class MainActivity extends Activity {

	private Button button;
	private MyApp myApp;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
				
		button = (Button)this.findViewById(R.id.button);
		myApp = (MyApp)getApplication();
		
		button.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				myApp.setName("thomas");
				
				Intent intent = new Intent(MainActivity.this, OtherActivity.class);
				startActivity(intent);
			}
		});
	}
}


MyApp


需要继承Application

public class MyApp extends Application {

	public String  name;

	public String getName() {
		return name;
	}

	public void setName(String string) {
		this.name = string;
	}
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
	
		setName("张三");
	}
}


OtherActivity

public class OtherActivity extends Activity {

	private MyApp myApp;
	private TextView textView;
	
	@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);
		myApp = (MyApp)getApplication();
		textView.setText("OtherActivity getName " + myApp.getName());
	}
}


试验效果


1



版权声明:本文为zhangxuechao_原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。