安卓学习笔记(一)、使用application传递数据


public class MainActivity extends Activity {
	public 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);
        button.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				myApp = (MyApp) getApplication();
				myApp.setName("jack");
				Intent intent = new Intent(MainActivity.this,OtherActivity.class);
				startActivity(intent);
			}
		});
    }



public class MyApp extends Application {
	public String name;

	public String getName() {
		return name;
	}

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



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("--appname-->>"+myApp.getName());
		
	}

}



        
            
                

                
            
        
        
        
    


你可能感兴趣的:(android)