问题
I have 16 Button
s 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:
- use Butterknife view injections library
- Download Android ButterKnife Zelezny plugin for
Android Studio
orIntellij 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