Button控件的三種點擊事件


①在布局文件中指定onClick屬性的方法設置點擊事件

 

 

 

 

 

 

 

 

②使用匿名內部類的方法設置點擊事件

 

 

 

 

 

 

 

 

③實現Activity實現OnClickListen接口的方式設置點擊事件

 

 

 

 

 

 

 

linear.xml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_one"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="按鈕1"
        />
    <Button
        android:id="@+id/btn_two"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="按鈕2"
        />
    <Button
        android:id="@+id/btn_three"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="按鈕3"
        />

</LinearLayout>

MainActivity代碼

package com.iang.buttonclick;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button  btn_one,btn_two,btn_three;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.linear);
        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_two.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               btn_two.setText("按鈕2已經被點擊");
           }
       });

       btn_three.setOnClickListener(this);
    }
//    通過在xml文件里定義click來監聽點擊事件
    public void click(View view){
       btn_one.setText("按鈕1已經被點擊");
    }

//    通過定義接口方法來監聽鼠標點擊事件
    @Override
    public void onClick(View v) {
        btn_three.setText("按鈕3已經被點擊");
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM