レイアウトに特定の種類のオブジェクト(テキストビュー、ボタン、またはイメージビューなど)がいくつあるかを知る方法はありますか?もちろん方法はありますが、どうやって始めたらいいのかわかりません。
2 に答える
2
次の再帰的な方法を使用してそれを行うことができます。
public int getChildrenCount(ViewGroup parent, Class type) {
int count = 0;
for(int i=0; i<parent.getChildCount(); i++) {
View child = parent.getChildAt(i);
if(child instanceof ViewGroup) {
count += getChildrenCount((ViewGroup) child, type);
}
else {
if(child.getClass() == type) {
// Try to find element name in XML layout
for(Field field : R.id.class.getDeclaredFields()) {
try {
int id = field.getInt(null);
if(id == child.getId()) {
String childName = field.getName();
}
} catch (Exception e) {
// error handling
}
}
//
count++;
}
}
}
return count;
}
たとえば、レイアウトTextView
内のすべての子を検索するには、次のようにします。activity_main
ViewGroup parent = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.activity_main, null);
int count = getChildrenCount(parent, TextView.class);
于 2013-01-21T09:01:38.513 に答える
0
getChildCount()とgetChildAt( )を使用して確認できます
例えば:
RelativeLayout fl = new RelativeLayout(this);
int childCount = fl.getChildCount();
int buttonCount = 0;
for (int i = 0; i < childCount; i++) {
if(fl.getChildAt(i) instanceof Button){
buttonCount++;
}
}
注:このメソッドは、ViewGroupの直接の子/子孫のみをチェックします。
于 2013-01-21T08:43:35.493 に答える