如何获取Activity的内容视图?

293

在调用 setContentView() 方法后,我应该调用哪个方法来判断一个活动是否有它的 contentView?

8个回答

544
this.getWindow().getDecorView().findViewById(android.R.id.content)
或者
this.findViewById(android.R.id.content)
或者
this.findViewById(android.R.id.content).getRootView()

5
或者 getWindow().findViewById(android.R.id.content) :) - Alex Lockwood
1
这个在获取父视图方面运行良好... 但是,如果我尝试 this.findViewById(android.R.id.content).setBackgroundDrawable(d); 它不起作用... 你能提供建议吗? 提前致谢 - Rajesh Wadhwa
3
如果您使用setContentView(R.layout.my_view)从XML安装布局,则会返回该布局的父级 - Jay Lieske
你好 @ernest,我有一个问题:如果我的布局中顶部有一张图片,然后是两个选项卡,底部有一个SatelliteMenu,想要在菜单项打开时进行模糊处理。 - Devendra Singh
1
Android.Resource.Id 中不存在该内容。 - Justin
显示剩余4条评论

23

如果您给布局设置一个ID,您就可以获得该视图的后退功能。

<RelativeLayout
    android:id="@+id/my_relative_layout_id"

并且从 findViewById 中调用它...


这是获取已安装布局根目录的最稳健方法。 - Jay Lieske
3
findViewById 方法需要传入一个布局元素的 ID,用于查找并返回相应的 View 对象。 - trans
2
@trans View contentView = findViewById(R.id.my_relative_layout_id); @trans 视图 contentView = findViewById(R.id.my_relative_layout_id); - Justin Liu

13

这个怎么样?

View view = Activity.getCurrentFocus();

这怎么可能没有更多的赞?非常好用! - aeskreis
1
@aeskries 因为在我的情况下它返回 null,所以我使用了 currentFocus?.let { ... } - user924

11

您可以尝试使用View.getRootView()方法。


5

您还可以覆盖 onContentChanged() 方法,该方法在调用 setContentView() 后被触发。


Ernest的答案将为您提供当前聚焦视图,即使它包含可滚动视图。 - YuDroid

3

如果您正在使用 Kotlin


    this.findViewById<View>(android.R.id.content)
                         .rootView
                         .setBackgroundColor(ContextCompat.getColor(this, R.color.black))

1

没有 "isContentViewSet" 方法。您可以在 setContentView 之前将一些虚拟的 requestWindowFeature 调用放入 try/catch 块中,如下所示:

try {
  requestWindowFeature(Window.FEATURE_CONTEXT_MENU);
  setContentView(...)
} catch (AndroidRuntimeException e) {
  // do smth or nothing
}

如果内容视图已经设置,requestWindowFeature 将抛出异常。


-3
我发现最好的选择,也是最不具侵入性的方法,就是在你的xml中设置一个标签参数,例如:

手机xml布局

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:tag="phone"/>

平板电脑 XML 布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:tag="tablet">

    ...

</RelativeLayout>

然后在你的活动类中调用它:

View viewPager = findViewById(R.id.pager);
Log.d(getClass().getSimpleName(), String.valueOf(viewPager.getTag()));

希望它对你有用。


4
这个回答如何回答这个问题? - Onik

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