安卓开发 一行代码为根布局下所有按钮设置监听

//为根布局下所有按钮设置监听

public void setOnClickListenerAllButtons(View.OnClickListener listener)

{

  //获取根布局

  ViewGroup group = (ViewGroup)((ViewGroup)findViewById(android.R.id.content)).getChildAt(0);

    setOnClickListenerAllButtons(group,listener);

}

 

//为所有按钮设置监听

private void setOnClickListenerAllButtons(View view,View.OnClickListener listener) {

  List<View> allchildren = new ArrayList<View>();

  if(view instanceof Button)

  {

  if(view.getId()!= -1)

  view.setOnClickListener(listener);

  }

  else if(view instanceof ImageButton)

  {

  if(view.getId()!=-1)

  view.setOnClickListener(listener);

  }

 

  else if (view instanceof ViewGroup) {

  ViewGroup vp = (ViewGroup) view;

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

    View viewchild = vp.getChildAt(i);

    setOnClickListenerAllButtons(viewchild,listener);

  }

  }

}

调用方法:

setOnClickListenerAllButtons(onClickListener);

    原文作者:风的影子XL
    原文地址: https://www.jianshu.com/p/4c5bfd56a546
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞