JoshChen安卓开发学习,从零开始(2)

2、效果2:页面的布局,垂直排列以及触发按钮,调用方法。

首先,我们在默认的主题下进行开发,何为默认的主题下呢?也就是上一篇 JoshChen安卓开发学习,从零开始(1)中的 AndroidManifest.xml 文件中android:theme删除掉。

然后我们再把 main.xml文件中 <RelativeLayout> 布局改为 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    //线性布局
    android:orientation="vertical" >

线性布局:是一个ViewGroup以线性方向显示它的子视图(view)元素,即垂直地水平地

接着:我们往里面添加一个按钮.

 <Button
        android:id="@+id/button1"
        //宽度的意思,fill_parent意思为:根据父窗口填满。也就像是html的width="100%".
        android:layout_width="fill_parent"
        //高度,根据内容来展示
        android:layout_height="wrap_content"
        android:text="Button" />

效果图如下:

下面我们再来添加事件触发:

android:onClick="button1_click" 

在上面的代码基础上,添加多一条事件。

在MainActivity.java的主窗体中,我们加入事件的处理方法。

public void button1_click(View view){
        DisplayToast("You have clicked the button1");
    }
    
    //为了方便测试,将内容显示。
    private void DisplayToast(String msg)
    {
        Toast.makeText(getBaseContext(), msg,
                Toast.LENGTH_SHORT).show();
    }

这样你就可以看到效果如下:

原文地址:https://www.cnblogs.com/cchulong/p/3428083.html