How to get all Buttons ID's in one time on Android

旧时模样 提交于 2020-06-24 07:37:41

问题


I have 16 Buttons in my Activity and I have to initialize those inside onCreate(). Is there any way to initialize all buttons in one single line code?(loops etc.) Code should take all buttons R.id. from XML Layout and process....


回答1:


Let's say you named your button button_0, button_1, .. button_15. You can do:

for (int i = 0; i < 16; i++) {
    int id = getResources().getIdentifier("button_"+i, "id", getPackageName());
    button[i] = (Button) findViewById(id);
}



回答2:


Well, if all 16 of those buttons are inside one view or layout, then you could do the following.

ArrayList<View> allButtons; 
allButtons = ((LinearLayout) findViewById(R.id.button_container)).getTouchables();

This assumes that your container (in this example a LinearLayout) contains no Touchable that is not a Button.




回答3:


  1. use Butterknife view injections library
  2. Download Android ButterKnife Zelezny plugin for Android Studio or Intellij IDEA and initialize all your views from current layout by 1 click



回答4:


For xamarin android :

List<Button>() allButtons = new List<Button>();
for (int i = 1; i < 15; i++)
{
    int id = this.Resources.GetIdentifier("btn" + i.ToString(), "id", this.PackageName);
    Button btn = (Button)FindViewById(id);
    allButtons.Add(btn);

}



回答5:


This method takes all buttons inside the layout, hope it helps. Easy to implement & you can use it for almost every project, no libraries required.

public List<Button> getAllButtons(ViewGroup layout){
        List<Button> btn = new ArrayList<>();
        for(int i =0; i< layout.getChildCount(); i++){
            View v =layout.getChildAt(i);
            if(v instanceof Button){
                btn.add((Button) v);
            }
        }
        return btn;
    }

Example

List<Button> btn_list = getAllButtons(myRelativeLayout);
Button my_btn = btn_list.get(0);
my_btn.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {
                Log.d("btn_test", "onClick: hello");
     }
});



来源:https://stackoverflow.com/questions/22639218/how-to-get-all-buttons-ids-in-one-time-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!