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

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

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 allchildren = new ArrayList();


  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);

你可能感兴趣的:(安卓开发 一行代码为根布局下所有按钮设置监听)