0

我是Android開發中的絕對新手,我發現使用將BitmapFactory.decodeResource()方法轉換爲實用程序類(不是活動類的類)。爲什麼我不能將BitmapFactory.decodeResource()方法用於實用類(不是活動的類)?無法解析方法getResources()

所以,我做我的代碼,一些重構,我有這個代碼行移動:

Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.chef_hat_ok); 

從活動類的方法,我的實用工具類中聲明的方法。

它好工作爲活動課,但INT移動到工具類方法,像這樣:

public class ImgUtility { 

    public Bitmap createRankingImg(int difficulty) { 

     // Create a Bitmap image starting from the star.png into the "/res/drawable/" directory: 
     Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.chef_hat_ok); 

     return myBitmap; 

    } 

} 

我獲得了getResources一個IDE錯誤消息()方法時,IDE說我:

無法解析法 'getResources()'

我認爲它公頃因爲getResources()方法檢索與活動類相關的內容。

展望舊代碼,我可以看到getResources()方法返回一個ContextThemeWrapper對象。我嘗試搜索AppCompatActivity類(因爲我的原始活動擴展它),但我找不到。

所以我的疑惑是:

1)的主要問題是:我怎麼能正確使用BitmapFactory.decodeResource()方法我previus ImgUtility CLAS裏面?

2)爲什麼當我使用BitmapFactory.decodeResource()方法它採取ContextThemeWrapper對象(由getResources(返回)方法)作爲參數?什麼代表這個對象?它涉及到一個活動課程還是什麼?聲明在哪裏?

TNX

回答

5

getResources()方法是在Context可用。你可以簡單地做到這一點在你的實用工具類:

public class ImgUtility { 

    public Bitmap createRankingImg(Context context, int difficulty) { 

     // Create a Bitmap image starting from the star.png into the "/res/drawable/" directory: 
     Bitmap myBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.chef_hat_ok); 
     return myBitmap; 

    } 

} 

要回答你的第二個問題,看到這一點:

java.lang.Object 
    ↳ android.content.Context 
     ↳ android.content.ContextWrapper 
      ↳ android.view.ContextThemeWrapper 
       ↳ android.app.Activity 

getResources()方法是在Context類實際存在。所有的插入類也有getResources()方法。因此,當你從Activity(這是Context的子類)調用getResources()時,它很容易被調用。

+0

好吧,但這個上下文代表什麼?那另一個問題呢? – AndreaNobili

+0

請參閱我的編輯。 –

1

getResources()實際上是Context類中的一種方法。 您仍然可以使用Utils類將上下文對象傳入Utils類。

請注意,這會在您的Utils類和Android Context類之間產生耦合,導致您無法直接在別處重新使用代碼。

至於第二個問題,我不能回答它,因此留給其他人。 :)

相關問題