【问题标题】:Why isn't there a getContentView() method for Activity?为什么 Activity 没有 getContentView() 方法?
【发布时间】:2018-04-09 17:39:15
【问题描述】:

Activity 类有一个setContentView() 方法。 PopupWindow 类有一个 getContentView() 方法,但没有其他方法。还有其他方法可以获取活动的主要内容视图吗?

【问题讨论】:

    标签: android android-layout android-view


    【解决方案1】:

    我能够通过此调用访问 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(), "");
    

    【讨论】:

    • +1 使用的 ViewGroup 视图 = (ViewGroup)getWindow().getDecorView();通过调用 view.removeAllViews() 清除活动中的所有视图; - 感谢您的回答!
    【解决方案2】:

    下面的代码可以解决问题:

    findViewById(android.R.id.content);
    

    本质上是一样的(需要在Activity的上下文中调用)

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 这也适用于 findViewById。我没有意识到您可以将 id 放在 xml 的最外层标记中。我是这样使用的:thisView = (View) findViewById(R.id.parent_view);
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-16
      • 2015-05-01
      • 2014-03-07
      • 2011-06-12
      • 2013-01-18
      • 2019-04-08
      相关资源
      最近更新 更多