Activity
一、创建Activity
二、注册Activity
三、启动Activity
四、关闭Activity
五、Activity生命周期
一、创建Activity:
在res/layout文件夹中创建一个布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#000000">
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="This is the a Activity"
android:layout_gravity="center_vertical"
android:background="#FFFFFF"
android:gravity="center_horizontal"/>
</LinearLayout>
在src文件夹中新建一个类继承Activity,使用setContentView加载布局文件
package com.example.activity;
import android.app.Activity;
import android.os.Bundle;
public class TowActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tow);//加载布局文件
}
}
二、注册Activity
在Manifest.xml中注册Activity
<!--这里主题设置为以对话框形式显示,方便后面查看生命周期-->
<activity android:name=".TowActivity"
android:theme="@android:style/Theme.Dialog">
</activity>
三、启动Activity
startActivity(MainActivity.this,TowActivity.class);
四、关闭Activity
finish();
五、Activity生命周期
直接上代码了
package com.example.activity;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Button btn_click;
private final String m_tag="lifecycle_tag";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_click=(Button)this.findViewById(R.id.btn_click);
btn_click.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
/*Dialog dialog= new Dialog(MainActivity.this);
dialog.show();*/
Intent intent=new Intent(MainActivity.this,TowActivity.class);
startActivity(intent);
}
});
Log.i(m_tag, "onCreate");
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
Log.i(m_tag, "onStart");
super.onStart();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
Log.i(m_tag, "onResume");
super.onResume();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
Log.i(m_tag, "onPause");
super.onPause();
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
Log.i(m_tag, "onStop");
super.onStop();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
Log.i(m_tag, "onDestroy");
super.onDestroy();
}
@Override
protected void onRestart() {
// TODO Auto-generated method stub
Log.i(m_tag, "onRestart");
super.onRestart();
}
}
大致分为:
创建(onCreate),销毁(onDistroy)
启动(onStart),停止(onStop)
恢复(onResume),暂停(onPause)(恢复:当前Activity可操作,可以理解为获得焦点,暂停失去焦点)
细节:
在Activity停止前失去焦点后即(onStop前,onPause后)执行
通常在这个方法中将其一些数据进行保存