1.布局中添加按钮:
在 first_layout.xml里添加按钮
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/button_1" //设置id为button_1 android:layout_width="match_parent" //宽度匹配界面 android:layout_height="wrap_content" //高度取合适,包含即可 android:text="Button_1" /> //按钮text
</LinearLayout>2.加载布局:
FirstActivity中加载布局
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.first_layout); }
项目添加的任何资源都会在R文件中生成一个相应的资源id.
故调用R.layout.first_layout就可以得到first_layout.xml的id,然后传入setContentView.
3.在AndroidManifest中注册:
注意! 是Manifest不是Mainfest!
AndroidStudio其实已经帮我们注册了.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.zx.activitytest"> <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" //省略了包名,外层已经定义 android:label="This is FirstActivity">
<intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter>
</activity> </application> </manifest>
我们需要配置主活动,即应用开启时启动哪个活动.
在activity标签内部加上Intent-filter标签,并码上图中代码.
这样我们就设置FirstActivity为主程序啦.
这是最基本的步骤,活动-布局-注册-设置活动为主活动.
本文介绍如何在Android应用中创建布局、添加按钮,并设置启动活动。包括在XML布局文件中添加按钮的方法、如何加载布局文件以及在AndroidManifest.xml中注册启动活动。

1072

被折叠的 条评论
为什么被折叠?



