Application的作用
Application可实现数据共享
例如:
一.新建一个空的工程,并新建一个App类,继承自Application
public class App extends Application { private String textData="default"; public void setTextData(String textData) { this.textData = textData; } public String getTextData() { return textData; } }
二.新建两个布局资源文件main1,main2,同时新建一个Main2类。main1.xml与main2.xml的内容相同,如下所示:
三.重写Main2.java的onCreate函数(MainActivity同)
private TextView textView; private EditText editText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main2); textView = (TextView) findViewById(R.id.textView); editText = (EditText) findViewById(R.id.editText); textView.setText("The share data is "+getApp().getTextData()); findViewById(R.id.btnSaveData).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((App)getApplication()).setTextData(editText.getText().toString());//保存数据到Application textView.setText("The share data is "+editText.getText().toString()); } }); } public App getApp(){ return (App) getApplicationContext(); }
四.修改AndroidManifest配置文件
<application android:name = ".App"//自定义的Aplication android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="Main1" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".Main2" android:label = "Main2"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application>
将两个Activity都定义为launcher类型。
五.运行结果