《第一行代码》学习笔记——探究活动(未完待续)

《第一行代码》学习笔记

一、探究活动
  1. 手动创建活动,不勾选 Generate Layout File 和 Launcher Activity

创建活动界面

  1. 重写onCreate()方法(每个活动都应该重写)
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}
  1. 新建 layout 布局,并在活动中加载布局
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // 加载布局
    setContentView(R.layout.first_layout);
}
  1. AndroidManifest.xml文件中注册
<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=".FirstActivity"></activity>
</application>

注:活动注册声明<activity>标签要放在<application>标签内

  1. 配置主活动
<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">
    <!--android:label显示的内容,既是标题栏内容,也是启动器中应用程序的名称-->
    <activity android:name=".FirstActivity"
        android:label="FirstActivity">
        <!--注册主活动-->
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
  1. 使用按钮触发 Toast 提醒
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.first_layout);
    Button button1 = (Button) findViewById(R.id.button_1);
    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(FirstActivity.this,
                "Button 1 被点击", Toast.LENGTH_SHORT).show();
        }
    });
}
  • 调用方法:
    • 通过静态方法makeText()创建出一个 Toast 对象
    • 调用show()将 Toast 显示出来
  • Toast 参数表
类型 描述
参数一 Context Toast 要求的上下文,一般为活动本身
参数二 text 要显示的文本内容
参数三 显示的时长,有两个内置常量可以选择,分别为:Toast.LENGTH_SHORTTOAST.LENGTH_LONG
  1. res下新建 menu目录

猜你喜欢

转载自www.cnblogs.com/lhlyzh/p/10052216.html