-
Specifically create an object that implements the xxx event listener interface, such as: Monitor1, and then button1.setOnXXX-Listener(monitor1); then [internal class]
Button button1 = (Button)findViewById(R.id.button1); class MyMonitor implements View.OnClickListener(){ public void onClick(View v){ switch(v.getId()){ case R.id.button1 : button1.setText("我被单击了!"); break; case....... } } } MyMonitor myMonitor = new MyMonitor(); //创建监听器对象 button1.setOnClickListener(myMonitor); //为 button1,指定单击事件监听器对象
-
Implement the listener interface of the current class, and then button1.setOnXXX-Listener(this); Then the abstract method of the listener interface (that is, the event processing method) must be implemented in the current class.
-
Methods using anonymous inner classes
View.OnClickListener myMonitor = new View.OnClickListener(){ //myMonitor 为 接口类型的引用变量,用于指向实现了该接口类型的 实现类的 对象 @Override //@Override 注解 : 一来便于阅读,二来防止写错重写方法,而被误认为是新方法。导致重写失败!】 public void onClick(View v){ button1.setText("我被单击了!"); } }// 此处是 创建了一个匿名内部类 【注意 ()内部类中】 Button button1 = (Button) findViewById(R.id.button1); button1.setOnClickListener(myMonitor);
-
In fact, the principle is the same as method 3, but the code is simple! [Event adapters (or listeners) are also commonly specified in this way in java]
Button button1 = (Button) findViewById(R.id.button1); button1.setOnClickListener(new View.OnClickListener(){ // 也是创建 实现了View.OnClickListener接口的 匿名内部类 @Override //【在jdk1.6时才能这样写,否则就不能写@Override,因为1.6以下不支持实现接口中的方法时 使用@Override 】 public void onClick(View v){ button1.setText("我被单击了!"); } });
-
Use the reflection mechanism to achieve, neither find controls nor set listeners ------ but not recommended
Set the onclick attribute for the (View) control in the layout file, and then write a method with the name of the onclick attribute value in the Activity corresponding to the layout. It must be
public and pass a View type parameter. --------It is more suitable for simple tests. uncommonly used- layout file:
<Button android:onClick="onClickButton1" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="利用反射机制触发事件处理方法" />
- In XXXActivity:
public void onClickButton1(View view){ Toast.makeText(MainActivity.this, "你点击了button1", Toast.LENGTH_SHORT).show(); }
- layout file:
[AndroidUI development - five ways of writing event monitoring]
Guess you like
Origin blog.csdn.net/UserFrank/article/details/129204941
Recommended
Ranking