안드로이드-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 View
s 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
'IT박스' 카테고리의 다른 글
동일한 테이블의 한 열에서 다른 열로 값 복사 (0) | 2020.06.06 |
---|---|
@IBDesignable 오류 : IB Designables : 자동 레이아웃 상태를 업데이트하지 못했습니다 : 인터페이스 빌더 Cocoa Touch Tool이 충돌했습니다 (0) | 2020.06.05 |
TypeError : sequence item 0 : 예상되는 문자열, int found (0) | 2020.06.05 |
Boolean의 null 값은 언제 사용해야합니까? (0) | 2020.06.05 |
Java에서 배열이 값으로 전달되거나 참조로 전달됩니까? (0) | 2020.06.05 |