Android开发积累

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

2019-02-24  本文已影响212人  风的影子XL

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

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

上一篇下一篇

猜你喜欢

热点阅读