对于下面发布的布局,我试图遍历整个布局并显示布局中每个视图的ID。 我用方法
尝试了下面发布的代码vg.getId()
但它为布局中的每个视图显示相同的ID
请您告诉我如何在布局中获取每个视图的唯一ID?
输出:
ew_1 I/ActMain: vg.getId() :2131427422
07-02 14:48:25.383 32647-32647/com.example.alteenos.test_traversethroughaview_1 I/ActMain: vg.getId() :2131427422
07-02 14:48:25.383 32647-32647/com.example.alteenos.test_traversethroughaview_1 I/ActMain: vg.getId() :2131427422
07-02 14:48:25.383 32647-32647/com.example.alteenos.test_traversethroughaview_1 I/ActMain: vg.getId() :2131427422
布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/actMain_mainContainer"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.altenos.test_traversethroughaview_1.ActMain">
<Button
android:id="@+id/actMain_btn_change"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/decision_postponed" />
<LinearLayout
android:id="@+id/actMain_linlay_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/actMain_btn_yes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/decision_accepted" />
<Button
android:id="@+id/actMain_btn_no"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/decision_rejected" />
</LinearLayout>
<TextView
android:id="@+id/actMain_tv_display"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="@+id/actMain_linlay_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
码:
private int countViews(ViewGroup vg) {
int childCount = vg.getChildCount();
for (int i = 0; i < childCount; i++) {
Log.i(TAG, "vg.getId() :" + vg.getId());
//if (vg.getChildAt(i) instanceof ViewGroup) {
//childCount += countViews((ViewGroup) vg.getChildAt(i));
//}
}
return childCount;
}
答案 0 :(得分:3)
您正在记录ViewGroup
的ID,而不是孩子。
答案 1 :(得分:1)
您应该登录View not ViewGroup
private int countViews(ViewGroup vg) {
int childCount = vg.getChildCount();
for (int i = 0; i < childCount; i++) {
Log.i(TAG,"vg.getId() :",vg.getChildAt(i).getId());
//Log.i(TAG, "vg.getId() :" + vg.getId()); Not this one
//if (vg.getChildAt(i) instanceof ViewGroup) {
//childCount += countViews((ViewGroup) vg.getChildAt(i));
//}
}
return childCount;
}