IT박스

안드로이드-View 안에 아이들을 넣습니까?

itboxs 2020. 6. 5. 21:12
반응형

안드로이드-View 안에 아이들을 넣습니까?


보기가 주어지면 그 안에 자식보기를 어떻게 얻을 수 있습니까?

그래서 사용자 정의보기가 있고 디버거 mChildren는 7 개의 다른보기가 있음을 보여줍니다 . 이러한 뷰에 액세스하는 방법이 필요하지만이를 수행하는 퍼블릭 API가없는 것 같습니다.

어떤 제안?

편집하다:

내 맞춤보기는 AdapterView


for(int index=0; index<((ViewGroup)viewGroup).getChildCount(); ++index) {
    View nextChild = ((ViewGroup)viewGroup).getChildAt(index);
}

그럴까요?


모든 직계 자녀뿐만 아니라 모든 자녀의 자녀 등을 얻으려면 재귀 적으로해야합니다.

private ArrayList<View> getAllChildren(View v) {

    if (!(v instanceof ViewGroup)) {
        ArrayList<View> viewArrayList = new ArrayList<View>();
        viewArrayList.add(v);
        return viewArrayList;
    }

    ArrayList<View> result = new ArrayList<View>();

    ViewGroup vg = (ViewGroup) v;
    for (int i = 0; i < vg.getChildCount(); i++) {

        View child = vg.getChildAt(i);

        ArrayList<View> viewArrayList = new ArrayList<View>();
        viewArrayList.add(v);
        viewArrayList.addAll(getAllChildren(child));

        result.addAll(viewArrayList);
    }
    return result;
}

결과를 사용하려면 다음과 같이 할 수 있습니다.

    // check if a child is set to a specific String
    View myTopView;
    String toSearchFor = "Search me";
    boolean found = false;
    ArrayList<View> allViewsWithinMyTopView = getAllChildren(myTopView);
    for (View child : allViewsWithinMyTopView) {
        if (child instanceof TextView) {
            TextView childTextView = (TextView) child;
            if (TextUtils.equals(childTextView.getText().toString(), toSearchFor)) {
                found = true;
            }
        }
    }
    if (!found) {
        fail("Text '" + toSearchFor + "' not found within TopView");
    }

View.findViewById () http://developer.android.com/reference/android/view/View.html#findViewById(int ) 를 통해 항상 자식 뷰에 액세스 할 수 있습니다 .

예를 들어 활동 /보기 내에서 :

...
private void init() {
  View child1 = findViewById(R.id.child1);
}
...

또는 뷰에 대한 참조가있는 경우 :

...
private void init(View root) {
  View child2 = root.findViewById(R.id.child2);
}

I'm just going to provide this answer as an alternative @IHeartAndroid's recursive algorithm for discovering all child Views in a view hierarchy. Note that at the time of this writing, the recursive solution is flawed in that it will contains duplicates in its result.

For those who have trouble wrapping their head around recursion, here's a non-recursive alternative. You get bonus points for realizing this is also a breadth-first search alternative to the depth-first approach of the recursive solution.

private List<View> getAllChildrenBFS(View v) {
    List<View> visited = new ArrayList<View>();
    List<View> unvisited = new ArrayList<View>();
    unvisited.add(v);

    while (!unvisited.isEmpty()) {
        View child = unvisited.remove(0);
        visited.add(child);
        if (!(child instanceof ViewGroup)) continue;
        ViewGroup group = (ViewGroup) child;
        final int childCount = group.getChildCount();
        for (int i=0; i<childCount; i++) unvisited.add(group.getChildAt(i));
    }

    return visited;
}

A couple of quick tests (nothing formal) suggest this alternative is also faster, although that has most likely to do with the number of new ArrayList instances the other answer creates. Also, results may vary based on how vertical/horizontal the view hierarchy is.

Cross-posted from: Android | Get all children elements of a ViewGroup


Here is a suggestion: you can get the ID (specified e.g. by android:id="@+id/..My Str..) which was generated by R by using its given name (e.g. My Str). A code snippet using getIdentifier() method would then be:

public int getIdAssignedByR(Context pContext, String pIdString)
{
    // Get the Context's Resources and Package Name
    Resources resources = pContext.getResources();
    String packageName  = pContext.getPackageName();

    // Determine the result and return it
    int result = resources.getIdentifier(pIdString, "id", packageName);
    return result;
}

From within an Activity, an example usage coupled with findViewById would be:

// Get the View (e.g. a TextView) which has the Layout ID of "UserInput"
int rID = getIdAssignedByR(this, "UserInput")
TextView userTextView = (TextView) findViewById(rID);

In order to refresh a table layout (TableLayout) I ended up having to use the recursive approach mentioned above to get all the children's children and so forth.

My situation was somewhat simplified because I only needed to work with LinearLayout and those classes extended from it such as TableLayout. And I was only interested in finding TextView children. But I think it's still applicable to this question.

The final class runs as a separate thread, which means it can do other things in the background before parsing for the children. The code is small and simple and can be found at github: https://github.com/jkincali/Android-LinearLayout-Parser

참고URL : https://stackoverflow.com/questions/8395168/android-get-children-inside-a-view

반응형