生活随笔
收集整理的這篇文章主要介紹了
Android学习笔记篇1. 从按钮的点击事件开始
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
布局:
在XML文件中寫三個(gè)按鈕,給它們不同的id:
(為按鈕2綁定點(diǎn)擊方法click:android:onClick=“click”)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:padding="8dp"tools:context=".MainActivity"><Buttonandroid:id="@+id/btn_one"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="按鈕1"/><Buttonandroid:id="@+id/btn_two"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="按鈕2"android:onClick="click"/><Buttonandroid:id="@+id/btn_three"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="按鈕3"/></LinearLayout>
在Java中編寫代碼,實(shí)現(xiàn)三種類型的按鈕的點(diǎn)擊事件:
(詳細(xì)看注釋)
package com.example.no_1;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;
import android.view.View;
import android.widget.Button;public class MainActivity extends AppCompatActivity implements View.OnClickListener {private Button btn_one
, btn_two
, btn_three
;@Overrideprotected void onCreate(Bundle savedInstanceState
) {super.onCreate(savedInstanceState
);setContentView(R.layout
.activity_main
);btn_one
= (Button)findViewById(R.id
.btn_one
);btn_two
= (Button)findViewById(R.id
.btn_two
);btn_three
= (Button)findViewById(R.id
.btn_three
);btn_three
.setOnClickListener(this);btn_one
.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view
) {btn_one
.setText("按鈕1被點(diǎn)擊");}});}public void click(View view
) {btn_two
.setText("按鈕2被點(diǎn)擊");}@Overridepublic void onClick(View view
) {switch (view
.getId()) {case R.id
.btn_three
:btn_three
.setText("按鈕3被點(diǎn)擊");}}
}
運(yùn)行,點(diǎn)擊三個(gè)按鈕,顯示設(shè)定文字:
總結(jié)
以上是生活随笔為你收集整理的Android学习笔记篇1. 从按钮的点击事件开始的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。