2011-03-11 71 views

回答

474
this.getWindow().getDecorView().findViewById(android.R.id.content) 

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

this.findViewById(android.R.id.content).getRootView() 
+36

'findViewById(android.R.id.content);'工作正常 – Blundell 2012-02-18 15:42:53

+4

或'getWindow()。findViewById(android.R.id.content)': ) – 2013-06-26 01:54:33

+0

这个工作正常,只要提取父视图有关... BUt ..如果我尝试 this.findViewById(android.R.id.content).setBackgroundDrawable(d); it剂量工作.. 你能请建议.. 在此先感谢 – 2013-08-02 09:08:56

8

您可能想试试View.getRootView()

19

如果您将ID添加到您的布局中,您可以获取视图。

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

而且从findViewById叫它...

+0

这是获取已安装布局的根的最稳健的方式。 – 2013-08-26 23:47:23

+3

你将什么传递给'findViewById'? – trans 2016-06-16 15:12:57

+0

@trans查看contentView = findViewById(R.id.my_relative_layout_id); – 2017-01-13 03:04:42

5

您还可以覆盖onContentChanged()这其中包括发射时setContentView()被调用。

+0

ernest的答案会给你当前的焦点视图,即使包含可滚动视图 – YuDroid 2012-09-08 14:06:56

1

没有“isContentViewSet”方法。你可以把一些虚拟的requestWindowFeature呼叫到try/catch块的setContentView之前是这样的:

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

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

7

如何

View view = Activity.getCurrentFocus(); 
-2

我找到的最好的选项和较少干扰,是设置标签PARAM你xml,如

PHONE 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"/> 

TABLET 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())); 

希望工程妳。

+2

这是如何回答这个问题? – Onik 2014-05-06 01:02:30