标签:protected 函数名 ann text button cti onclick nullable android
常用方式为匿名类和本类监听的方法。其中本类监听方法需要继承View.OnClickListener接口之后,重写onClick方法。
PS:重写某一个方法的快捷键为Ctrl+O
package com.example.kimberjin.reviewpro; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.Toast; /** * Created by KimberJin on 2018/7/25. */ public class ButtonListenerTest extends AppCompatActivity implements View.OnClickListener{ private Button btn1, btn2, btn3, btn4, btn5; //btn5是布局监听,需要在对应的xml文件中设置onClick属性,其后跟一个函数名。 //然后在MainActivity中实现函数 @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_button); btn1 = (Button)findViewById(R.id.my_Btn1); btn2 = (Button)findViewById(R.id.my_Btn2); btn3 = (Button)findViewById(R.id.my_Btn3); btn4 = (Button)findViewById(R.id.my_Btn4); btn5 = (Button)findViewById(R.id.my_Btn5); //内部类监听 btn1.setOnClickListener(new BtnClick()); //外部类监听 btn2.setOnClickListener(new MyButtonListener()); //本类监听 btn3.setOnClickListener(this); //匿名类监听 btn4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(getBaseContext(), "匿名类监听", Toast.LENGTH_SHORT).show(); } }); } class BtnClick implements View.OnClickListener { @Override public void onClick(View view) { Toast.makeText(getBaseContext(), "内部类监听", Toast.LENGTH_SHORT).show(); } } @Override public void onClick(View view) { Toast.makeText(this, "本类监听", Toast.LENGTH_SHORT).show(); } public void getInfo(View view) { Toast.makeText(getBaseContext(), "布局监听", Toast.LENGTH_SHORT).show(); } } class MyButtonListener extends ButtonListenerTest implements View.OnClickListener{ @Override public void onClick(View view) { Toast.makeText(view.getContext(), "外部类监听", Toast.LENGTH_SHORT).show(); } }
标签:protected 函数名 ann text button cti onclick nullable android
原文地址:https://www.cnblogs.com/viva-futbol/p/9509500.html