zoukankan      html  css  js  c++  java
  • View的setOnClickListener的添加方法

    1)第一种,也是最长见的添加方法(一下都以Button为例)

    1 Button btn = (Button) findViewById(R.id.myButton);
    2 btn .setOnClickListener(new View.OnClickListener() {
    3 public void onClick(View v) {
    4 //do something
    5 }
    6 });



    2)第二种,下面这个方法较前一种稍微简单了一些,允许多个Buttons共享一个Listener。通过Switch控制对不同Button Click事件的响应方法:

    复制代码
     1 Button btn = (Button) findViewById(R.id.mybutton);
    2 Button btn2 = (Button) findViewById(R.id.mybutton2);
    3 btn.setOnClickListener(handler);
    4 btn2.setOnClickListener(handler);
    5 View.OnClickListener handler = View.OnClickListener() {
    6 public void onClick(View v) {
    7 switch (v.getId()) {
    8 case R.id.mybutton:
    9 //do something
    10 break;
    11 case R.id.mybutton2:
    12 //do something
    13 break;
    14 }
    15 }
    复制代码




    3)第三种,直接将Clicklistener捆绑XML layout中的Views元素,在程序中定义的Listener方法需要带有一个View类型的参数:

    复制代码
     1 <?xml version="1.0" encoding="utf-8"?>
    2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    3 android:orientation="vertical" android:layout_width="fill_parent"
    4 android:layout_height="fill_parent">
    5 <TextView android:layout_width="fill_parent"
    6 android:layout_height="wrap_content" android:id="@+id/text"
    7 android:text="@string/hello" />
    8 <Button android:id="@+id/mybutton" android:layout_height="wrap_content"
    9 android:layout_width="wrap_content" android:onClick="mybuttonlistener"></Button>
    10 </LinearLayout>
    复制代码

    java代码:

    1 Button btn = (Button) findViewById(R.id.mybutton);
    2
    3 public void mybuttonlistener(View target){
    4 //do something
    5 }
     
  • 相关阅读:
    Apache日志分析
    iptables日志探秘
    php与其他一些相关工具的安装步骤分享
    ERROR 1 (HY000): Can't create/write to file '/tmp/#sql_830_0.MYI' (Errcode: 13)
    一些可能需要的正则
    restful api的简单理解
    认识MySQL Replication
    如何处理缓存失效、缓存穿透、缓存并发等问题
    经典算法mark
    php常用的一些代码
  • 原文地址:https://www.cnblogs.com/hack0573/p/4906185.html
Copyright © 2011-2022 走看看