添加第一个控件Button
在Android中,打开res -> layout (若没有layout文件,则在res中新建一个)右键layout文件,新建 Layout resource file 此xml文件(若有***_main.xml,则不用新建,点开即用)
打开activity_main.xml文件
可能文件不同,此处要在文件中添加LinearLayout布局元素,以及下面代码块中的Button控件。
其中:
- android:id是给当前元素定义一个唯一标识符,之后可以在这个代码中对这个元素进行操作。
- android:layout_width指定此控件的宽度。
- android:layout_height制定此控件的高度。
- match_parent表示让这个控件跟父元素一样,在此处的父元素是此界面,也就是让这个Button的宽度占满一行。
- warp_content表示当前元素的长度只要刚好包含里面的内容就行。在此处也就是让高度能够包含文字内容。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 1"/>
</LinearLayout>
然后就要给此Button添加一个布局。
打开Activity.java文件,加入如下代码:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
其中 setContentView(R.layout.activity_main); 给当前活动加载了一个布局,布局文件为R.layout.activity_main
这样第一个Button控件添加完成。