Android 实现按钮监听的 4 种方式
- 创建成员内部类
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.button); Button but1 = (Button) findViewById(R.id.but01); //生成监听器类的对象 ButtonListener buttonListener = new ButtonListener(); //为按钮添加监听器 but1.setOnClickListener(buttonListener); } //内部类 class ButtonListener implements View.OnClickListener { @Override public void onClick(View view) { Toast.makeText(MainActivity.this, "按钮被点击", Toast.LENGTH_SHORT).show(); } } }
- 创建匿名内部类
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.button); Button but1 = (Button) findViewById(R.id.but01); //为按钮添加监听器 but1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this, "按钮被点击", Toast.LENGTH_SHORT).show(); } }); } }
- Activity 直接实现监听接口
public class MainActivity extends AppCompatActivity implements View.OnClickListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.button); Button but1 = (Button) findViewById(R.id.but01); //为按钮添加监听器 but1.setOnClickListener(this); } @Override public void onClick(View view) { Toast.makeText(MainActivity.this, "按钮被点击", Toast.LENGTH_SHORT).show(); } }
- XML 文件OnClick 属性实现监听
xml 布局文件中,为button添加onclick属性;
在对应的Activity中创建一个以onclick属性值为名字的方法
修饰符为public 返回值为void 传入参数为View类型
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.button); } public void buttonClick(View v){ Toast.makeText(MainActivity.this,"xml实现的监听被点击了",Toast.LENGTH_LONG).show(); } }
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"> <Button android:id="@+id/but01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="xml 实现监听按钮" android:onClick="buttonClick"/> </LinearLayout>