安卓基础(六)

来源:互联网 发布:麻将棋牌辅助软件 编辑:程序博客网 时间:2024/04/29 13:20

交互是必不可少的

  • 交互是必不可少的
    • 简介
    • 正文
    • 扩展阅读

目标人群:没有基础的安卓初学者
知识点:为Button控件添加点击事件
目标:通过点击页面的按钮来改变文字的显示内容

简介

  • 本章会简单的介绍如何通过点击页面上的按钮来改变页面上的文字显示内容

  • 本章需要少量Java语法知识,方法的概念

正文

1.为activity_main.xml布局中添加一个Button控件,添加后的布局如下所示

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:orientation="vertical"    android:layout_height="match_parent">    <TextView        android:id="@+id/textView"        android:text="@string/hello_world"        android:layout_width="wrap_content"        android:layout_height="wrap_content" />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="点击"        android:id="@+id/button" /></LinearLayout>

2.为该Button控件添加点击属性,添加后的Button代码如下

       <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="点击"        android:onClick="changeTxt"        android:id="@+id/button" />

不难发现,我们为这个Button添加了一个值为changeTxt的android:onClick属性。

3.回到MainActivity.java页面中,在页面中添加changeTxt方法,同布局文件中的Button点击属性相对应。

    public void changeTxt(View view){        //得到文字控件对象,并对文字内容进行设置        TextView textView = (TextView) findViewById(R.id.textView);        textView.setText("你好,世界!");    }

4.重新Build你的项目,并在模拟器上运行,尝试点击Button,点击后的效果如下图所示

这里写图片描述

扩展阅读

  1. Button的那些事
  2. 输入事件概述
0 0
原创粉丝点击