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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3736367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 11:35:59  来源:igfitidea点击:

Why isn't there a getContentView() method for Activity?

androidandroid-layoutandroid-view

提问by kencorbin

The Activityclass has a setContentView()method. The PopupWindowClass has a getContentView()method but nothing else does. Is there another way to get the main content view for an activity?

这个Activity类有一个setContentView()方法。该PopupWindow班有一个getContentView()方法,但没有别的一样。是否有另一种方法可以获取活动的主要内容视图?

回答by mikeplate

I was able to get to the contents of an Activity with this call:

通过此调用,我能够访问 Activity 的内容:

ViewGroup view = (ViewGroup)getWindow().getDecorView();

You should probably check that getDecorView returns an instanceof ViewGroup for all cases, but with a LinearLayout in the Activity the code above runs fine. To get to the LinearLayout you could then just:

您可能应该检查 getDecorView 是否在所有情况下都返回 ViewGroup 的实例,但是在 Activity 中使用 LinearLayout 时,上面的代码运行良好。要进入 LinearLayout,您可以:

LinearLayout content = (LinearLayout)view.getChildAt(0);

And if you have a function like this:

如果你有这样的功能:

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 + " ");
    }
}

You could iterate through all views and log their class names with the following call inside your Activity:

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

logContentView(getWindow().getDecorView(), "");

回答by moonlightdock

Following line will do the trick:

以下行可以解决问题:

findViewById(android.R.id.content);

it is essentially same as (it needs to be called on the context of an Activity)

它本质上与(需要在活动的上下文中调用)相同

this.findViewById(android.R.id.content);

回答by bibby

I'm looking for this as well, but I just thought that it might be easier to add an id to the outermost ViewGroup.

我也在寻找这个,但我只是认为将 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">

I'll keep looking for a few more minutes, though. I'm into it so that I can use findViewWithTagfrom the outermost layout.

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