2011-03-11 44 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