为什么没有Activity的getContentView()方法?

ken*_*bin 51 android android-layout android-view

这个Activity班有一个setContentView()方法.该PopupWindow班有一个getContentView()方法,但没有别的一样.有没有其他方法来获取活动的主要内容视图?

mik*_*ate 51

我能够通过此调用获取活动的内容:

ViewGroup view = (ViewGroup)getWindow().getDecorView();
Run Code Online (Sandbox Code Playgroud)

您应该检查getDecorView是否为所有情况返回ViewGroup的实例,但是在Activity中使用LinearLayout,上面的代码运行正常.要进入LinearLayout,您可以:

LinearLayout content = (LinearLayout)view.getChildAt(0);
Run Code Online (Sandbox Code Playgroud)

如果你有这样的功能:

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 + " ");
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以遍历所有视图并使用Activity中的以下调用记录其类名:

logContentView(getWindow().getDecorView(), "");
Run Code Online (Sandbox Code Playgroud)


moo*_*ock 50

以下行将做到这一点:

findViewById(android.R.id.content);
Run Code Online (Sandbox Code Playgroud)

它与(它需要在Activity的上下文中调用)基本相同

this.findViewById(android.R.id.content);
Run Code Online (Sandbox Code Playgroud)


bib*_*bby 3

我也在寻找这个,但我只是认为向最外面的 ViewGroup 添加 id 可能会更容易。

<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">
Run Code Online (Sandbox Code Playgroud)

不过,我会继续寻找几分钟。我很喜欢它,这样我就可以从最外面的布局使用findViewWithTag 。