2016-06-07 6 views
0

두 가지 테마가있어 동적으로 전환 할 수 있습니다.정의 된 속성을 사용하여 색상을 동적으로 변경하는 방법

는 themes.xml에서

<attr name=“txtColor” format="reference" /> 

attrs.xml이에 정의 된 txtColor 속성이있다, 속성을 사용하여, 레이아웃 파일에서 다른 테마

<style name=“CustomLight" parent="AppTheme.Base"> 
    <item name="txtColor”>#000000</item> 

<style name=“CustomDark" parent="AppTheme.Base"> 
    <item name="txtColor”>#ffffff</item> 

의 속성에 대한 색상을 정의 괜찮 으면

android:textColor="?attr/txtColor" 

사용하려고하면 예외가 발생합니다. txtColor 속성

Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x7f010015 
txtView.setTextColor(getResources().getColor(R.attr.txtColor)); 

질문 : 속성을 사용하여 색상을 동적으로 변경하는 방법은 무엇입니까?

+0

당신은 당신이'txtView.setTextColor 호출하는 방법을 표시 할 수 있습니다() (의 GetResources getColor에서 (R.attr.txtColor).)' – Akis

+0

@Akis이, 당신이 무엇을 물어 확실하지, 그것은 텍스트 뷰와 txtView입니다 .setTextColor()를 사용하여 색상을 설정합니다 (색상 자원 ID가 있어야 함). – lannyf

답변

1

첫 번째 속성의 형식은 "컬러"

<attr name="txtColor" format="color"/>

그런 다음 당신이하고있는 색상을 설정할 수 있어야한다 : 내가 함께 일 간단한 해결책을 찾은 것 같아요

int[] attrs = {R.attr.txtColor} ; 
try { //getPackageManager() can throw an exeption 
    Activity activity = getActivity(); 
    themeId = activity.getPackageManager().getActivityInfo(activity.getComponentName(), 0).theme; 
    TypedArray ta = activity.obtainStyledAttributes(themeId, attrs); 
    int color = ta.getColor(0, Color.BLACK); //I set Black as the default color 
    txtView.setTextColor(color); 
    ta.recycle(); 
} catch (NameNotFoundException e) { 
    e.printStackTrace(); 
} 
1

를 기존의 attrs, 여기 누군가가 똑같은 것을 찾고 있다면, 어떤 더 단순한 것들을 찾고 있습니까? 감사!

public static int getColorByThemeAttr(Context context, int attr, int defaultColor) { 
    TypedValue typedValue = new TypedValue(); 
    Resources.Theme theme = context.getTheme(); 
    boolean got = theme.resolveAttribute(attr, typedValue, true); 
    return got ? typedValue.data : defaultColor; 
}