您的位置:首页 > 移动开发 > Android开发

超级原创xxMix android:onClick上帝啊,不知道有没有人用过,我用了,在网上好多鸟回答乱七八糟,自己找到了

2011-11-30 13:38 363 查看
超级原创xxMix android:onClick上帝啊,不知道有没有人用过,我用了,在网上好多鸟回答乱七八糟,自己找到了

android:onClick = “xx”

 

 

 

public void (View v) 记得函数参数匹配  根据多态性以及函数指针原理这里的函数会注册给android:onClick的监听器

 这样每个button都可以使用onClck定义自己测处理方法,也可以共用,但是关于事件源的区分就没有那么方便了,可能需要获取坐标才能逻辑上判断是哪个按钮或者根据

 

完整例子

main.xml

<?xml version="1.0"encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<Button
android:onClick = "xxx"
android:text="ok" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button
android:onClick = "xxx"
android:text="no" android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
MainActivity.java

package com.sms;

 

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.Toast;

 

public class MainAcitivy extends Activity {

   /** Called when the activity is first created. */

   @Override

   public void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       setContentView(R.layout.main);

    }

 

   public void xxx(View v)

             {

                       //可以直接转型但是注意有时候子类不匹配  ((Button)v).getText()

                       Button temp = (Button)v;   //最好用instanceof判断子类型的实例,,注意子类型和子类不一样,面向对象设计原理

                       if(temp.getText().toString().trim().equalsIgnoreCase("ok"))

                                {

                                         Toast.makeText(this,"ok ", Toast.LENGTH_SHORT).show();

                                }

                       if(temp.getText().toString().trim().equalsIgnoreCase("no"))

                                {

                                         Toast.makeText(this,"no ", Toast.LENGTH_LONG).show();

                                }

                      

             }

   public void xxxx(View v)  //也可以单独映射自己的方法,但是单独写代码过于冗余 所以建议统一 使用getText判断仍然是好方法,需要记住处理函数参数

             {

                       Toast.makeText(this,"xxxx", Toast.LENGTH_SHORT).show();

             }

}

 

 

按钮上的文字区分事件源
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐