Activity.addContentView(View)和ViewGroup.addContentView(View)一样吗?

14
我有关于Android Activity的一个问题:
一个Activity有一个方法addContentView(View),而一个ViewGroup有一个(类似的?)addView(View)方法。
不幸的是,文档没有说明addContentView中的View放置在哪里。它是否像LinearLayout一样只将View添加到底部,还是更像FrameLayout,将其视图添加到“onTop”?这取决于由setContentView设置的ViewGroup吗?
如果我深入源代码,我会看到addContentView将调用Window的抽象方法addContentView。不幸的是,我看不到实现此方法的类。那么Activity的addContentView的行为究竟如何?
2个回答

46
每个活动的基本布局都是一个 FrameLayout。这意味着你通常通过 setContentView() 设置的布局是该布局的子类。addContentView() 仅添加另一个子元素,因此它的行为类似于 FrameLayout (这意味着它会在现有元素上方添加新的UI元素)
你可以使用名为 hierarchyviewer 的工具从 ANDROID_SDK\tools 文件夹中检查此功能。以下是两个屏幕截图:

enter image description here

在调用addContentView()之前,这是布局,我的活动包括默认的FrameLayout,其中包含一个带有按钮的LinearLayout(这是我的布局)。这反映在这里的底部行,上面的其他元素是标题/状态栏。

enter image description here

在使用addContentView()添加一个TextView后,它看起来是这样的。您可以看到基本的FrameLayout有了一个新的子元素。

4
哇,非常感谢你的回答,谢谢。你提供的提示和工具将节省我很多时间!你是使 Stackoverflow 如此伟大的那种用户! - Rafael T
Hierarchiviewer并未被弃用,但有一个选项。 - Ivandro Jao

0
public void addContentView(View view,
              LayoutParams params) {
  mActivity.addContentView(view, params);
}

//

public static void SetActivityRoot(Activity c) {
      View v = ((ViewGroup)c.findViewById(android.R.id.content)).getChildAt(0);
    
      ScrollView sv = new ScrollView(c);
      LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,
          LayoutParams.MATCH_PARENT);
      sv.setLayoutParams(lp);
    
      ((ViewGroup) v.getParent()).removeAllViews();
    
      sv.addView((View) v);
      c.addContentView(sv, lp);
    }

//

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  LinearLayout mainLayout = 
    (LinearLayout)findViewById(R.id.mainlayout);
  
  //newButton added to the existing layout
  Button newButton = new Button(this);
  newButton.setText("Hello");
  mainLayout.addView(newButton);
  
  //anotherLayout and anotherButton added 
  //using addContentView()
  LinearLayout anotherLayout = new LinearLayout(this);
  LinearLayout.LayoutParams linearLayoutParams = 
    new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.WRAP_CONTENT,
      LinearLayout.LayoutParams.WRAP_CONTENT);
  
  Button anotherButton = new Button(this);
  anotherButton.setText("I'm another button");
  anotherLayout.addView(anotherButton);
  
  addContentView(anotherLayout, linearLayoutParams);
 }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接