Android开发之编写第一个Android应用程序实现按钮和复选框
搞Android系统这么久了,说实话,我连apk怎么写还真是不会,说实话能够看懂,简单改改就不错了,说来惭愧,我是嵌入式出身。最近开始学习Android应用开发,和我的底层结合起来,为了工作,咬着牙也要学下去!!!
首先,我使用的是Android Studio这个软件。
上谷歌中国网就可以下载到了,地址如下:
https://developer.android.google.cn/develop/index.html
编译环境配置,找百度看看就行了,这里不哆嗦。
安装好后,有一些工具没有安装到位可能会报下面类似的错误,看着下面的log提示找解决方案就行了,不懂就百度。作为一个开发人员,错误信息要会看。
程序实现的界面,功能如下:
(1)按下ALL ON/OFF,所有的复选框checkbox被全部选中或者全部不选中,且按钮里的字符串变成ALL ON或者ALL OFF,并打印消息led all on或者led all off
(2)勾选或者不勾选checkbox,会选中对应的LEDx,并打印对应LED on或者 LED off
首先看下Activity_main.xml,这个文件是以上这个界面的布局文件,路径在res/layout/activity_main.xml
笔记:
(1)Layout的宽度和高度,用wrap_content表示取决于它的内容
android:layout_width="wrap_content"
android:layout_height="wrap_content"
(2)表示宽度会填充整个窗口
fill_parent
(3)线性垂直
把RelativeLayout 改为如下xml代码的 LineraLayout
android:orientation="vertical" 这一行表示垂直
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
android:orientation="vertical"
>
@顺序排列--->按垂直方向
<TextView android:text="First Android progame"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
@指定ID
<Button
android:id="@+id/BUTTON"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="ALL ON/OFF"
/>
<CheckBox
android:id="@+id/LED1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="LED1"
android:onClick="onCheckboxClicked"
/>
<CheckBox
android:id="@+id/LED2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="LED2"
android:onClick="onCheckboxClicked"
/>
<CheckBox
android:id="@+id/LED3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="LED3"
android:onClick="onCheckboxClicked"
/>
<CheckBox
android:id="@+id/LED4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="LED4"
android:onClick="onCheckboxClicked"
/>
</LinearLayout>
如何在布局中添加控件?如上,要添加一个控件,那么就 <控件名称 /> 在这里面添加相关的信息。
最关键的就是id。Android Studio这个软件很智能,有自动补全功能,没有的上网百度或者参考文档。
如图,打开谷歌中国,右上角,搜索,比如Button:
搜索Button会弹出:
选择android.widget.Button,会弹出以下界面:
参考的编写代码,案例都在下面,看看就会写了,非常简单。
