【发布时间】:2018-04-09 17:39:15
【问题描述】:
Activity 类有一个setContentView() 方法。 PopupWindow 类有一个 getContentView() 方法,但没有其他方法。还有其他方法可以获取活动的主要内容视图吗?
【问题讨论】:
标签: android android-layout android-view
Activity 类有一个setContentView() 方法。 PopupWindow 类有一个 getContentView() 方法,但没有其他方法。还有其他方法可以获取活动的主要内容视图吗?
【问题讨论】:
标签: android android-layout android-view
我能够通过此调用访问 Activity 的内容:
ViewGroup view = (ViewGroup)getWindow().getDecorView();
您可能应该检查 getDecorView 是否在所有情况下都返回一个 instanceof ViewGroup,但是在 Activity 中使用 LinearLayout 时,上面的代码运行良好。要使用 LinearLayout,您可以:
LinearLayout content = (LinearLayout)view.getChildAt(0);
如果你有这样的功能:
void logContentView(View parent, String indent) {
Log.i("test", indent + parent.getClass().getName());
if (parent instanceof ViewGroup) {
ViewGroup group = (ViewGroup)parent;
for (int i = 0; i < group.getChildCount(); i++)
logContentView(group.getChildAt(i), indent + " ");
}
}
您可以在 Activity 中使用以下调用遍历所有视图并记录其类名:
logContentView(getWindow().getDecorView(), "");
【讨论】:
下面的代码可以解决问题:
findViewById(android.R.id.content);
本质上是一样的(需要在Activity的上下文中调用)
this.findViewById(android.R.id.content);
【讨论】:
我也在寻找这个,但我只是认为将 id 添加到最外层的 ViewGroup 可能更容易。
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/outer">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
不过,我会继续寻找几分钟。我喜欢它,这样我就可以从最外面的布局中使用findViewWithTag。
【讨论】: