2012-10-29 16 views
37

我想從上下文中獲取視圖或findViewById()? 或從意圖?android - 如何從上下文中獲取視圖?

我試圖達到我的廣播接收器中的特定視圖和onReceive的參數是上下文和意圖。

嗯,我有一個類,它內部是我的廣播接收器。現在,我試圖將廣播接收器與它分開,但我需要一種方法,以便我仍然可以通過分離的廣播接收器類與我的課堂上的視圖進行通信。

謝謝。

回答

5

在你的廣播接收器,你可以通過通貨膨脹從XML資源訪問視圖根佈局,然後找到這個根佈局findViewByid()所有的觀點:

View view = View.inflate(context, R.layout.ROOT_LAYOUT, null); 

現在,您可以通過訪問您的看法「視圖」,並將其投射到您的視圖類型:

myImage = (ImageView) view.findViewById(R.id.my_image); 
+0

應該是什麼我放在根參數? – lorraine

+0

根參數是充氣層次結構的根視圖。在上面的例子中,我展示瞭如何膨脹一個已經是根的視圖,因此你可以保持這個參數爲false。如果您的虛擬視圖不是根目錄,則將您的根視圖作爲第三個參數。 –

+3

不應該是'null'而不是'false'嗎? – Roberto

43

與上下文開始,相關活動的根視圖可以通過

View rootView = ((Activity)_context).Window.DecorView.FindViewById(Android.Resource.Id.Content); 
可以了

在原始的Android它會看起來像:

View rootView = ((Activity)mContext).getWindow().getDecorView().findViewById(android.R.id.content) 

然後只需調用findViewById這個

View v = rootView.findViewById(R.id.your_view_id); 
+3

請記住,您應該將'View v = rootView.findViewById(R.id.your_view_id);'轉換爲'View v =(View)rootView.findViewById(R.id。your_view_id);而類_View_可以是View的派生類。 –

+1

當我嘗試這個時,我得到「引起:java.lang.ClassCastException:android.app.Application無法轉換爲android.app.Activity」。 – drynyn

+2

@drynyn這是因爲這個例子假定一個Activity被傳遞給上下文,這不是一個安全的假設。您可以使用instanceof關鍵字來檢查演員是否安全執行。 (谷歌「instanceof java」爲例)。 – eimmer

1

第一次使用這樣的:

LayoutInflater inflater = (LayoutInflater) Read_file.this 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

Read file is current activity in which you want your context. 

View layout = inflater.inflate(R.layout.your_layout_name,(ViewGroup)findViewById(R.id.layout_name_id)); 

那麼你可以使用這個在佈局中查找任何元素。

ImageView myImage = (ImageView) layout.findViewById(R.id.my_image); 
41

例如,你可以找到任何的TextView:

TextView textView = (TextView) ((Activity) context).findViewById(R.id.textView1); 
+3

很好的答案。這是2015年的做法,上述方式似乎非常多餘。 –

0

你爲什麼不只是使用一個單身?

import android.content.Context; 


public class ClassicSingleton { 
    private Context c=null; 
    private static ClassicSingleton instance = null; 
    protected ClassicSingleton() 
    { 
     // Exists only to defeat instantiation. 
    } 
    public void setContext(Context ctx) 
    { 
    c=ctx; 
    } 
    public Context getContext() 
    { 
     return c; 
    } 
    public static ClassicSingleton getInstance() 
    { 
     if(instance == null) { 
      instance = new ClassicSingleton(); 
     } 
     return instance; 
    } 
} 

然後在活動類:

private ClassicSingleton cs = ClassicSingleton.getInstance(); 

而在非活動類:

ClassicSingleton cs= ClassicSingleton.getInstance(); 
     Context c=cs.getContext(); 
     ImageView imageView = (ImageView) ((Activity)c).findViewById(R.id.imageView1);