2013-12-18 1 views
2

다음 스크립트를보다 효율적으로 만들 수있는 방법이 있습니까? 이 코드를 쉽게 유지 보수 할 수있게 만들고 싶습니다. 왜 내가 if else if를 없애고 싶습니다. 여러분이 나를 도와 줄 수 있기를 바랍니다. 밑바닥에는 내가보고 싶은 무언가가 있습니다. 물론 그렇게 할 수 있다면.문자열을 R.color에 사용하십시오. "string"

 if (category.equals("infusion")){ 
     layout.setBackgroundResource(R.color.infusion); 
      title.setText(R.string.title_infusion);    
    } else if (category.equals("pills")){ 
      layout.setBackgroundResource(R.color.pills); 
      title.setText(R.string.title_pills); 
    } else if (category.equals("pumps")){ 
      layout.setBackgroundResource(R.color.pumps); 
      title.setText(R.string.title_pumps); 
    } else if (category.equals("oxygen")){ 
      layout.setBackgroundResource(R.color.oxygen); 
      title.setText(R.string.title_oxygen); 
    } else if (category.equals("scores")){ 
      layout.setBackgroundResource(R.color.scores); 
      title.setText(R.string.title_scores); 
    } else if (category.equals("converters")){ 
      layout.setBackgroundResource(R.color.converters); 
      title.setText(R.string.title_converters); 
    } 

이와 비슷한 기능이 있습니까?

layout.setBackgroundResource(R.color.*category*); 
title.setText(R.string.title_*category*); 

답변

3

나는 모든 것들을 당신이 "간단하게"이 포함 것이다 반사를 할 것이라고 확신, 그리고 아마도 코드가 느린하고 이해하기 어려워 끝나는 것입니다. 당신이 가지고있는 것은이 일을하는 완벽하게 유효한 방법이며, 독자들에게는 매우 명확하며 이상한 기술은 필요하지 않습니다.

I.E. 이 방법이 효과가 있습니까?

확인, 편집 :

당신이 해시 맵을 통해 ID를 자원하기 위해 문자열 값을 매핑 할 수 있습니다 시작합니다. 같은

뭔가 : 나중에 다음

HashMap map = new HashMap(); 
map.put("infusion",R.id.infusion); 

과 :

layout.setBackgroundResource(map.get(category)); 
title.setText(category); 

그 힘 작동하지만 다시는 정말 IMO 개선이 아니다. 그런 다음 그것을 사용하는

public static int resourceNameToId(Context context, String name, String resType) { 
    if (name != null && name.length() > 0) { 
     return context.getResources().getIdentifier(name, resType, context.getPackageName()); 
    } 

    return 0; 
} 

:

+2

가 – JoeC

2

체크 아웃 Resources.getIndentifier() 같은 도우미 함수를 가질 수

layout.setBackgroundResource(resourceNameToId(getContext(), category, "color")); 
+0

파산하지 않은 경우 나 또한이 내부 반사를 사용하고 문서에서 가볍게 – FunkTheMonk

+0

사용하는 것을 말해야한다 : 참고 :이 기능의 사용은 권장하지 않습니다. 이름보다는 식별자로 자원을 검색하는 것이 훨씬 더 효율적입니다. –

+0

그래, 나는 어댑터를 넣을 것을 제안하지는 않겠지 만 동적으로 생성 된 콘텐츠에 매우 유용 할 수 있습니다. 또한 능률적으로, 나는 OP가 유지 보수성에 더 관심이 있다고 생각한다. – FunkTheMonk

0

당신은 당신의 코드를 건설하여이를 달성 할 수 없다. 같은

사용 무언가 :

layout.setBackgroundResource(getColorByCategory(category)); 
title.setText(getCategoryTitle(category)); 

getColorByCategory()getCategoryTitle() 자신의 기능입니다.

0

내 머리 꼭대기에서 생각할 수있는 두 가지 방법이 있습니다. 해시 맵 및 또는 Resources 객체 사용

layout.setBackgroundColor(COLOURS.get(category)); 

당신은 색상이 오는 확인 null로 할 수 있습니다 : 그것은 나중에 색상을 설정하는 것은 매우 쉽습니다 그리고

private static final Map<String, Integer> COLOURS = new HashMap<String, Integer>(); 

static { 
    COLOURS.put("pills", R.color.red); 
    COLOURS.put("pumps", R.color.green); 
} 

:

A는 맵과 같이 약간의 설정을 포함하는 것이있다 가지고있는 데이터가 완벽하다는 보장이 없다면 맵을 설정하기 전에지도에서 벗어나십시오.

또는 이와 같이 Resources 개체를 사용할 수 있습니다.

당신은 당신의 가치와 색상을 유지하는 다음과 같이 열거를 사용할 수
2

Resources resources = context.getResources(); 
resources.getColor(resources.get("colour_" + category, "color", context.getPackageName())); 
: 당신이해야 할 열거를 사용할 수

public enum ColorValue { 

InFusion(android.R.color.black), 
Pills(android.R.color.white); 

int color; 

ColorValue(int Value) { 
    color = Value; 
} 

public int getColorResource() { 
    return color; 
} 

} 

다음이

ColorValue x=ColorValue.InFusion; 
x.getColorResource(); 
0

유사한 열거 값에 액세스를 더 효과적입니다 :

(클래스에서) 신고하십시오

public enum Category { 
    infusion (R.color.infusion, R.string.title_infusion, "infusion"), 
    pills (R.color.pills, R.string.title_pills, "pills") //, 
    //etc... comma-seperated values. Those are handled like any other enum 
    ; 
    public final int relatedBackground; 
    public final String relatedTitle; 
    public final String identifier; //To keep the identifiers you used previously 

    private Category (int back, String title, String id) { 
     this.relatedBackground = back; 
     this.relatedTitle = title; 
     this.identifier = id; 
    } 
} 

과 같을 것이다 당신의 방법

public void foo(Category cat) { //You pass in your enum type 
    //Do what you want 
    if(cat != null) { //Avoid NullPointerException if necessary 
     layout.setBackgroundResource(cat.relatedBackground); 
     title.setText(cat.relatedTitle); 
    } 
} 

이 방법을 사용하면 에 의해 프로젝트는 을 유지할 수 있기 때문에 당신이있어 문제에 새로운 값을 추가를 해결하는 좋은 방법입니다 쉼표로 구분 된 목록. 당신은 또한 필요가 없습니다에 대해 걱정할 필요가 때마다 조회 테이블에서.

단점는 런타임 동안 열거 을 조정할 /하드 불가능하다는 것이다. 열거의 모든 변수는 enumtype로 최종해야 당신이 당신이 통근 테이블을 사용 할 것이다 그렇게하려면 자체는

cat.relatedbackground = someValue; // Can't do that: all fields are final 

등의 작업을 수행 할 수 없습니다 수정되지 않습니다. 그 외에도 우수한 솔루션입니다.