程式內有兩個Activity , 於Activity1按下按鈕"Go To Activity2" 時 , Activity 會被開啟 , 點選Activty2的Back to Activity1按鈕時 , 則會將Activity2關閉 , 同時回傳訊息 , 而題目希望透過Log來驗證Activity的生命週期 , 這題用意在測驗考生清不清楚 Activity Lifecycle , 如果清楚的話這題是相當簡單的 , 再配合Log顯示Activity的當前狀態即可 , 另外兩個Activity之間的資料往返 , 在記得要在AndroidManifest.xml 宣告另一支Activity , 以下是程式碼。
package COM.TQC.GDD01; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; public class GDD01 extends Activity { private static final String TAG = "Android_Log"; private TextView tv; private Button b1; private Button b2; final int ACT1 = 1; private Intent intent; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv=(TextView) findViewById(R.id.text1);; b1 = (Button) findViewById(R.id.button1); b2 = (Button) findViewById(R.id.button2); intent = new Intent(); intent.setClass(this, GDD1_2.class); b1.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { startActivityForResult(intent,ACT1); } }); b2.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { finish(); } }); Log.i(TAG, "onCreate()"); } @Override public void onActivityResult (int requestCode, int resultCode, Intent data) { tv.setText(""+resultCode); } @Override public void onStart() { super.onStart(); Log.i(TAG, "onStart()"); } @Override public void onResume() { super.onResume(); Log.i(TAG, "onResume()"); } @Override public void onPause() { super.onPause(); Log.i(TAG, "onPause()"); } @Override public void onStop() { super.onStop(); Log.i(TAG, "onStop()"); } @Override public void onRestart() { super.onRestart(); Log.i(TAG, "onRestart()"); } @Override public void onDestroy() { super.onDestroy(); Log.i(TAG, "onDestroy()"); } }
package COM.TQC.GDD01; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class GDD1_2 extends Activity { Button backButton; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mylayout); backButton = (Button) findViewById(R.id.button2); backButton.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { GDD1_2.this.setResult(99); finish(); } }); } }
接下來是簡單的Layout
不要忘記AndroidManifest.xml 的宣告
P.S. 題目中所要求的Variable和Method皆會保留 , 也會根據題目所要求的流程去實作 , 縱使題目要求繞遠路....
沒有留言:
張貼留言