Android SDK Tutorial: Button onClick Event
16lz
2021-01-23
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.
Now when you the click button:
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>
更多相关文章
- Android 下载图片的问题
- Android View转换成图片保存
- Unity调用Android保存图片到相册
- Android图片压缩
- 【Android】android图片轮播
- Android:EditText插入图片实现图文混排
- Android之GLES2.0显示图片测试代码
- Android 自定义ProgressBar--进度自己设置图片
- Android 本地图片多选