Android Studio開發基礎之Context用法說明

來源:互聯網
上載者:User

標籤:

1、Context說明       

       Context是一個用於訪問全域資訊的介面,如應用程式的資源(片,字串等),一些常用的組件繼承自Context,如Activity和Service等等。

       如利用Java代碼建立一個textView,textView的第一種setText()方法直接傳入一個字串,第二種setText()方法傳入一個整形的id(位於values\\strings.xml下面的hello_world,即:<string name="hello_world">Hello world!</string>),最後將setContextView改為setContextView(textView)。

public class MainActivity extends ActionBarActivity {    private TextView textView;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        //setContentView(R.layout.activity_main);        textView=new TextView(MainActivity.this);        //textView.setText("Hello GeoStorm");        textView.setText(R.string.hello_world);                setContentView(textView);    }}
       以上代碼中,雙擊第一個setText()方法,按F4,即可看到該建構函式,入口參數為字串。

public final void setText(CharSequence text) {        setText(text, mBufferType);    }
       雙擊第一個setText()方法,按F4,即可看到該建構函式,入口參數為resid,其內部的setText()即為第一個setText()方法,getContext()即為我們建立TextView時傳入的MainActivity.this!!!
    public final void setText(int resid) {        setText(getContext().getResources().getText(resid));    }

       在看了建構函式之後,我們也可以按照建構函式裡的,進行下面的原始寫法:

    //textView.setText(R.string.hello_world);    textView.setText(getApplicationContext().getResources().getText(R.string.hello_world));
       同樣,我們也可以訪問圖片資源:
public class MainActivity extends ActionBarActivity {    private TextView textView;    private ImageView imageView;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        //setContentView(R.layout.activity_main);        //textView=new TextView(MainActivity.this);        //textView.setText("Hello GeoStorm");        //textView.setText(R.string.hello_world);        //textView.setText(getApplicationContext().getResources().getText(R.string.hello_world));                imageView=new ImageView(this);//可以直接使用this        imageView.setImageResource(R.mipmap.ic_launcher);        setContentView(imageView);    }}

2、Application的應用及說明

       現在我們用Context來實現組件之間資訊的共用。建立一個App.java類用來傳遞資料,繼承自Application,增加一個字串變數,並添加讀寫建構函式,如下:

package com.example.lhb.context;import android.app.Application;public class App extends Application {    public String S="DefaultString";    public void setS(String s) {        S = s;    }    public String getS() {        return S;    }}
       接下來進行AndroidManifest配置:在Application中加入android:name=".App",並添加另一個Activity,名為Main2。在設定檔中加入跟MainActivity一樣的配置,其中 <action android:name="android.intent.action.MAIN" />說明在手機案頭上出現兩個應用程式。

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.lhb.context" >    <application        android:name=".App"        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=".MainActivity2Activity"            android:label="Main2" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>
       Main1中和Main2加入如下同樣的代碼:

package com.example.lhb.context;import android.support.v7.app.ActionBarActivity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.EditText;import android.widget.ImageView;import android.widget.TextView;public class MainActivity extends ActionBarActivity {    private TextView textView;    private EditText editText;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        textView= (TextView) findViewById(R.id.textView);        editText= (EditText) findViewById(R.id.editText);        //讀取預設的字串        textView.setText("共用的資料是:"+((App)getApplicationContext()).getS());        findViewById(R.id.btnSave).setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                ((App)getApplicationContext()).setS(editText.getText().toString());                textView.setText(String.format("共用的資料是:%s",editText.getText().toString()));            }        });    }}
效果如下:

          

3、Application生命週期

       重寫建構函式並執行,結果發現App.java的onCreate()函數在任何一個Activity的onCreate()函數之前執行,這對於我們做初始化操作非常有用。

package com.example.lhb.context;import android.app.Application;public class App extends Application {    public String S="DefaultString";    public void setS(String s) {        S = s;    }    public String getS() {        return S;    }    @Override    //建立時執行    public void onCreate() {        super.onCreate();        System.out.println("App OnCreate");    }    @Override    //結束時執行,一般不執行,只在類比環境中執行    public void onTerminate() {        super.onTerminate();        System.out.println("App on Terminate");    }    @Override    //低記憶體時執行    public void onLowMemory() {        super.onLowMemory();    }    @Override    //清理記憶體時執行    public void onTrimMemory(int level) {        super.onTrimMemory(level);    }}





Android Studio開發基礎之Context用法說明

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.