Android 通过Application 传递数据

</pre><pre>
package com.example.ApplicationTest;

import android.app.Application;

/**
 * Created by chang on 14-10-1.
 */
public class App extends Application {
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String name;

    @Override
    public void onCreate() {
        super.onCreate();

        setName("张三");
    }
}
package com.example.ApplicationTest;

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

public class MyActivity extends Activity {

    private Button btnLaunch = null;
    private App myApp;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btnLaunch = (Button)this.findViewById(R.id.btnLaunch);
        myApp = (App)this.getApplication();
        myApp.setName("hello");

        btnLaunch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MyActivity.this,OtherActivity.class);
                startActivity(intent);
            }
        });


    }
}

package com.example.ApplicationTest;

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

/**
 * Created by chang on 14-10-1.
 */
public class OtherActivity extends Activity {
    private App myApp;
    private TextView textView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.other);
        textView = (TextView)findViewById(R.id.showMsg);
        myApp = (App)getApplication();

        textView.setText(myApp.getName());
    }
}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.ApplicationTest"
          android:versionCode="1"
          android:versionName="1.0">

    <uses-sdk android:minSdkVersion="19"/>
    <application
            android:label="@string/app_name"
            android:icon="@drawable/ic_launcher"
            android:name=".App">
        <activity
                android:name="MyActivity"
                android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

        <activity android:name=".OtherActivity" >

        </activity>
    </application>
</manifest>



郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。