0

I have a main activity and it shows (with setContentView) different xml layout based on user action so main activity does not know witch layout is set and cannot access them by findbyid.

The task of my main activity is just read all objects in xml file like TextView, button,... and save the id and value of them in a hash table to use in the different class in application framework. The class in the framework knows those objects and can work with them.

the question is how can I get all object in the view and have access to their id and value?

maryam
  • 251
  • 4
  • 11
  • 1
    Do you have a View instance of your layout to get all the ids in it? Or do you only have the layout id? – Sherif elKhatib Dec 04 '13 at 16:01
  • I have layout id. but I think I can get a view instance with this code: setContentView(R.layout.activity_1); LayoutInflater inflater = LayoutInflater.from(activity_1.this); View theInflatedView = inflater.inflate(R.layout.activity_1, null); haven't tried that yet. – maryam Dec 04 '13 at 16:05
  • Is not clear what you want to achieve. Can you post some code? Btw, this may help you http://stackoverflow.com/questions/4872238/enumerate-iterate-all-views-in-activity – ivan.aguirre Dec 04 '13 at 16:06
  • `setContentView` must be set only once per activity. If you want more than one view at same activity, use fragments. – ramaral Dec 04 '13 at 16:11

1 Answers1

1

Never tested but here is a simple implementation. You can use it using

List<Integer> ids = new ViewIdEnumerator(yourView).getIds();

Here is the implementation of ViewIdEnumerator.

package mobi.sherif.so;

import java.util.ArrayList;
import java.util.List;

import android.view.View;
import android.view.ViewGroup;

public class ViewIdEnumerator {
    List<Integer> ids;
    public ViewIdEnumerator(View v) {
        ids = new ArrayList<Integer>();
        enumerate(v);
    }

    public List<Integer> getIds() {
        return ids;
    }
    private void enumerate(View child) {
        if (child == null)
            return;

        if (child instanceof ViewGroup) {
            enumerate((ViewGroup) child);
        }
        else if (child != null) {
            ids.add(child.getId());
        }
    }

    private void enumerate(ViewGroup parent) {
        ids.add(parent.getId());
        for (int i = 0; i < parent.getChildCount(); i++) {
            View child = parent.getChildAt(i);
            if (child instanceof ViewGroup) {
                enumerate((ViewGroup) child);
            } else {
                enumerate(child);
            }
        }
    }
}
Sherif elKhatib
  • 45,786
  • 16
  • 89
  • 106