1.什么是Acivity
用户交互界面:在无边界的天空打开了一个天窗。
2.运行一个简单的Activity
2.1 JAVA:
package com.field.activitydemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
/**
* MainActivity 需要 继承 AppCompatActivity
*
*/
public class MainActivity extends AppCompatActivity {
//2.对象的使用范围 是否定义全局变量
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//3.给当前活动绑定布局
setContentView(R.layout.activity_main);
//4.初始化view 用于加载控件 注意控件只有在先加载 然后再调用,否则会报空指针
initView();
}
private void initView() {
//加载控件
mTextView = findViewById(R.id.tv);
}
}
2.2 XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/root"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!--xml 创建文本控件 注意需要在代码中需要给控件对象 使用 setter getter方法的时候 加上id
设置text的时候 最好用存入res,values ,strings 内部
方便本地化-->
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/hello_man"/>
</RelativeLayout>
2.3 AndroidManifest.xml:
如果自定义的Activity没有在这里注册,会报异常:
Unable to find explicit activity class ..; have you declared this activity in your AndroidManifest.xml?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.field.activitydemo">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".LifeActivity"></activity>
<!--配置文件 将MainActivity 注册在AndroidManifest.xml -->
<activity android:name=".MainActivity">
<!--过滤器 app启动后 打开的主界面 action 表示是主界面 category 表示启动
备注:可以给app 设置多个 启动界面 会有意想不到的效果-->
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
3.小记:
java 代码控制与用户交互的数据。xml 显示view(修改xml编译的时间 大于 修改代码编译的时间)。