One OnClickHandler for multiple Buttons

后端 未结 6 2077
再見小時候
再見小時候 2020-11-28 23:09

I find myself doing things like this all the time:

    Button button1 = (Button) findViewById(R.id.button1);
    Button button2 = (Button) findViewById(R.id.         


        
6条回答
  •  清酒与你
    2020-11-29 00:05

    I think in case, when your buttons are not in Activity but in FragmentDialog, etc., this can help

    Context mContext = getActivity().getBaseContext();
    mRes = mContext.getResources();
    String[] idOfButtons = { "button1", "button2", "button3"};
    for (int pos = 0; pos < idOfButtons.length; pos++) {
       Integer btnId = mRes.getIdentifier(idOfButtons[pos], "id",(getActivity()).getBaseContext().getPackageName());
        ImageButton ib = (ImageButton) v.findViewById(btnId);
        ib.setOnClickListener(this.onClickNum);
    }
    

提交回复
热议问题