android - Android 中的委托(delegate)(常见)点击监听器

标签 android button click touch listener

假设我有几个按钮,它们的点击由通用处理程序处理,是否有一种方法可以定义一次监听器,而不是为每个按钮定义 onClick 属性?

<Button android:onClick="handler" />

也许是浏览器或某些拦截器中的父委托(delegate).....想象一下您有 50 个按钮,您明确声明每个按钮的点击???

最佳答案

是的,你可以这样做。

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
List<Button> buttons;
ViewGroup parentView;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    buttons = new ArrayList<>();
    parentView = (ViewGroup) findViewById(R.id.cord);


    //Replace the above line with the container view i.e.
    //Replace  parentView = (ViewGroup) findViewById(R.id.cord);
    // With parentView = (ViewGroup) findViewById(R.id.<YOUR MAIN VIEW/PARENT CONTAINER>);
    //R.id.cord is R.id.<YOUR MAIN VIEW/PARENT CONTAINER> for me because my Relative Layout 
    // container's name is cord.


    for(int i=0; i < parentView.getChildCount(); i++) {

        childView = parentView.getChildAt(i);
        //The if may change there are other options try them too.
        if(childView.getClass().getName().substring(35).equals("Button")){


            buttons.add((Button)parentView.getChildAt(i));
        }
        /*
        //Else part optional 
        //Remove comment to use
        else
            Log.e("Not","A Button");*/
    }

    for (int i =0;i<buttons.size();i++){
        buttons.get(i).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Do the work here
                Log.d("Button Clicked",Integer.toString(view.getId()));
            }
        });
    }





    }
}

这是解决问题的一种方法...

关于android - Android 中的委托(delegate)(常见)点击监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46735752/

相关文章:

c# - 仅在 wpf 上显示 X 和最小化按钮

wpf - 如何禁用某些按钮的加速键

java - Selenium 说元素点击了 'successfully' ,但是,它实际上并没有被点击

java - 使用动态形状获取鼠标检测

javascript - 如何在页面加载时单击具有相同类的所有输入

android - 尝试检查网站可用性时超时

android - TextView : scale down and scale up with sequential animations

android - 如何在 Android 中从 AsyncTask 实现 Web 服务连接?

c# - 删除按钮的蓝色轮廓

android - 导入现有的 Android 项目导致 JNI 文件夹中有很多 "bugs"