牛下载:绿色软件官方软件免费下载基地!
所在位置:首页 > 新闻资讯 > Android按钮单击事件的五种实现方式

Android按钮单击事件的五种实现方式

发布时间:2020-04-22 20:55:41来源:阅读:

匿名内部类作为事件监听器

public class MainActivity extends Activity {

 private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(new OnClickListener() {
         @Override
         public void onClick(View v) {
             System.out.println("匿名内部类作为事件监听器");
         }
     });

    }

}

内部类作为事件监听器

public class MainActivity extends Activity {

 private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(new ButtonOnClickListener());
    }

    class ButtonOnClickListener implements OnClickListener{
     @Override
     public void onClick(View v) {
         System.out.println("内部类作为事件监听器");
     }
    }

}

Activity本身作为事件监听器

public class MainActivity extends Activity implements OnClickListener{

 private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
     System.out.println("Activity本身作为事件监听器");
    }

}

外部类作为事件监听器

public class MainActivity extends Activity {

 private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(new ButtonOnClickListener());
    }

}
class ButtonOnClickListener implements OnClickListener {

 @Override
 public void onClick(View v) {
     System.out.println("外部类作为事件监听器");
 }

}

将事件处理方法直接绑定到标签

<Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="点击事件"
            android:onClick="onClick" />
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onClick(View v){
     System.out.println("将事件处理方法直接绑定到标签");
    }

}
反对
收藏
  • 热门资讯
  • 最新资讯
  • 应用排行榜
  • 游戏排行榜