«

android 控件onClick事件的4种实现方式

时间:2024-3-2 17:49     作者:韩俊     分类: Android


1、

<span style="white-space:pre">     </span>TextView tv = (TextView) findViewById(R.id.tv);
        tv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                //do something...
            }
        });

2、

<span style="white-space:pre">     </span>TextView tv = (TextView) findViewById(R.id.tv);
        OnClickListener mOnClickListener = new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                //do something...
            }
        };
        tv.setOnClickListener(mOnClickListener);

3、

package com.yqy.yqy_click;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {

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

    @Override
    public void onClick(View view) {
        // TODO Auto-generated method stub
        switch (view.getId()) {
        case R.id.tv:
            //do something...
            break;

        default:
            break;
        }
    }

}

4、

<!-- android:clickable="true" 设置可点击权限 ( Button,ImageButton,等本身具有点击的事件的控件不用设置 )-->
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:clickable="true"
        android:text="@string/hello_world" />
<span style="white-space:pre"> </span>public void onClick(View view){
        //do something...
    }



标签: android

热门推荐