2017-06-05 14 views
1

私のコードを2つのプロジェクトに分割して、すべての私の将来のプロジェクトに共通する機能を備えたSDKを用意しました。Androidはコンテキストのテーマからプログラムで(「R」に直接アクセスすることなく)リソースを取得します

私は、あるプロジェクトのXMLファイルの値を他のものから取り出すという問題を抱えています。たとえば、styles.xmlで色を取得しなければなりませんでした。カスタム色はattrs.xmlで定義された「iconColor」です。ここに私がしたことがあります:

TypedValue typedValue = new TypedValue(); 
Resources.Theme theme = context.getTheme(); 
int colorIdentifier = context.getResources().getIdentifier("iconColor", "attr", context.getPackageName()); 
if (theme.resolveAttribute(colorIdentifier, typedValue, true)) { 
    return typedValue.data; 
} 
else { 
    return 0; 
} 

そして、あるプロジェクトから別のプロジェクトにうまくいきます。別の目的のために、私は私のコンテキストのテーマのcolorPrimaryを取得したかったのです。

/** 
* Retrieves a resource from context's theme using the resource id 
* 
* @param resId the resource id, ie. android.R.attr.colorPrimary 
* @return the resource value, or null if not found 
*/ 
public @Nullable Integer getResourceFromTheme(int resId) { 
    Integer result = null; 

    TypedValue typedValue = new TypedValue(); 
    Resources.Theme theme = context.getTheme(); 
    if (theme.resolveAttribute(resId, typedValue, true)) { 
     result = typedValue.data; 
    } 

    return result; 
} 

/** 
* Retrieves a resource from context's theme using the resource name 
* 
* @param resName the resource name, ie. "colorPrimary" 
* @return the resource value, or null if not found 
*/ 
public @Nullable Integer getResourceFromTheme(@NonNull String resName) { 
    int resId = context.getResources().getIdentifier(resName, "attr", context.getPackageName()); 
    return getResourceFromTheme(resId); 
} 

私は、理論的にはカスタムだけでなく、android.Rを使用してネイティブのプロパティを取得することができるように:私はここでそれが今ある方法です、一般的な機能を持っている私のコードを微調整しました。しかし、まだ私のcostom iconColorプロパティのために働いている、私はcolorPrimaryを取得することはできません、それは間違ったデータを返しています。私はコードを間違って持って意味の一つの方法または他のを、使用しようとする場合であっても奇妙、私は別の値を得た:

enter image description here

答えて

1

オーケーの機能が正常に動作しているが、私は2つのミスを犯したので、xxxxはありますColorResとaaaa/bbbbはColorIntで、R.attr.colorPrimaryの代わりにandroid.R.attr.colorPrimaryを使用して関数を呼び出していました。

関連する問題