Making your app notice when a button was clicked is pretty simple, the code am giving you here is what I found to be the shortest method to do so.

The Result

We will make a button that updates a label with the current date when you click it. Pictures below.

The app before a button click


Now when you the click button:
Android SDK Tutorial: Button onClick Event_第1张图片

After the click: the text was updated to the current date.

The Button Click Class (HelloAndroid.java)

package com.example.helloandroid;import java.util.Date;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.TextView;public class HelloAndroid extends Activity{TextView date;@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);date=(TextView)findViewById(R.id.dateText);}public void showNewDate(View v){date.setText(new Date().toString());}}

The Android Manifest(AndroidManifest.xml)

Don’t forget to change android:minSdkVersion to the version you are using.

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="com.example.helloandroid"      android:versionCode="1"      android:versionName="1.0">    <uses-sdk android:minSdkVersion="13" />    <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true">        <activity android:name=".HelloAndroid"                  android:label="@string/app_name">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>

The Layout(main.xml)

The line android:onClick is saving us from typing many more JAVA code lines. The value is the method in the JAVA file we want to execute when a user clicks the button.

<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"><TextViewandroid:text="You haven't clicked"android:id="@+id/dateText"android:layout_width="wrap_content"android:layout_height="wrap_content" /><Button    android:id="@+id/button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Click Me"  android:onClick="showNewDate"/></LinearLayout>

更多相关文章

  1. Android 下载图片的问题
  2. Android View转换成图片保存
  3. Unity调用Android保存图片到相册
  4. Android图片压缩
  5. 【Android】android图片轮播
  6. Android:EditText插入图片实现图文混排
  7. Android之GLES2.0显示图片测试代码
  8. Android 自定义ProgressBar--进度自己设置图片
  9. Android 本地图片多选

随机推荐

  1. 【ArcGIS for Android】使用自定义Callou
  2. Android颜色透明度
  3. Android的Button属性使用
  4. android 屏幕保持不锁屏
  5. 《敏捷开发》发版记录
  6. Android高仿微信相册选择器 多图片选择器
  7. Android三方库依赖中的maven坐标详解
  8. Android面试、笔试、期中/末考试复习提纲
  9. Android(安卓)5.1开机自启动示例程序(Act
  10. Android(安卓)7.1 AppOpsManager默认允许