0

What I am trying to do is get every ID of every button in an android fragment. Currently I have a for loop that runs through the ID that are "PA1", "PA2", "PA3" .... I want to be able to use any ID but still modify it with java code.

This is what I have now

TextView tv;
View viewHold;

Button[] btns;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.pri_all_view, container, false);
    viewHold = view;

    int resId=-1;
    int c=0;
    while(resId != 0){
        resId = getResources().getIdentifier("PA" + (c+1), "id", MainActivity.PACKAGE_NAME);
        c++;
    }
    btns = new Button[c-1];

    for(int i=0;i < btns.length; i++){
        resId = getResources().getIdentifier("PA" + (i+1), "id", MainActivity.PACKAGE_NAME);
        btns[i] = (Button) view.findViewById(resId);
        btns[i].setTransformationMethod(null);
        btns[i].setOnClickListener(this); // calling onClick() method
    }
    return view;
   }
....

This does work but I dont want to have to use a generic ID with a number after it.

Josh Young
  • 125
  • 3
  • 15

1 Answers1

0

I will assume your buttons are all in the same view group. If not, you will need to make recursive calls to handle subviews.

Not sure if you want to save the references of buttons, or the references of button IDs. As I read the question, I guess you need button IDs.

Declare in your fragment a field variable List<Integer> (named for instance "buttonIDs").

Then, in your onCreateView :

ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.pri_all_view, container, false);

for (int i=0; i < rootView.getChildCount(); i++) {
    View v = rootView.getChildAt(i);
    if (v instanceof Button) {
        buttonIDs.add(v.getId());
    }
}

If you want to use your IDs :

for (int id : buttonIDs) {
    Button btn = (Button)rootView.findViewById(id);
}
doubotis
  • 219
  • 2
  • 10