2012-08-03 4 views
3

Android XML 레이아웃 파일에서 두 개의보기 사이의 관계를 지정하고 싶습니다.Android XML : XML 레이아웃 파일에서 리소스 ID를 View 태그로 설정하십시오.

<View 
     android:id="@+id/pathview" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" /> 
    ... 
    <CheckBox 
     android:id="@+id/viewPath" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:checked="true" 
     android:paddingRight="7dp" 
     android:shadowColor="#000000" 
     android:shadowDx="0.5" 
     android:shadowDy="0.5" 
     android:shadowRadius="0.5" 
     android:tag="@id/pathview" 
     android:text="Paths" /> 

그러나, XML 파서는 문자열로 태그를 치료하고 ("false"를 System.out.println((String) [viewPath].getTag()); 인쇄) 정수로 해석하지 : 여기에 내가하고 싶은 것입니다. View의 태그에 리소스 ID를 할당 할 수있는 방법이 있습니까?

+1

http://stackoverflow.com/questions/5100381/how-to-set-an-array-as-tag-to-any-view-through-layout-xml-in-android –

답변

1

id 문자열을 태그로 설정 한 다음 id를 가져올 수 있습니다.

일부 같은 :

<View 
    android:id="@+id/pathview" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" /> 
... 
<CheckBox 
    android:id="@+id/viewPath" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:checked="true" 
    android:paddingRight="7dp" 
    android:shadowColor="#000000" 
    android:shadowDx="0.5" 
    android:shadowDy="0.5" 
    android:shadowRadius="0.5" 
    android:tag="pathview" 
    android:text="Paths" /> 

그런 다음 코드 :

CheckBox viewPath = findViewById(R.id.pathview); 
String pathViewStrId = (String) viewPath.getTag(); 
int patViewId = getResources().getIdentifier(pathViewStrId, "id", getPackageName()); 
View pathView = findViewById(patViewId); 
2

당신이

android:tag="?id/pathview" 

당신이 질문 접두사 진수 정수로 문자열 ID를 얻을 것이다 사용하는 경우 표. 이 동작에 대한 설명서를 찾을 수 없지만 충분히 안정적으로 보입니다. 당신이하고있는 일은 현재 테마의 ID를 요청하는 것입니다. 왜 결과 문자열에 '?'접두사가 붙는 이유는 무엇입니까? 알 수 없습니다. 예를 들어

: 일부 식별자 감안할 때

,

public static final int test_id=0x7f080012; 

일,
android:tag="?id/test_id" 

는 태그 값 발생합니다 :

"?2131230738" 

그런 다음 할 수 있습니다 :

View otherView = activity.findViewById(
    Integer.parseInt(
     someView.getTag().toString().substring(1) 
    ) 
); 

물론 일반화 된 논리를 작성하는 경우 null 대신 태그를 확인하고 NumberFormatException을 catch 할 수 있습니다.

+0

위대한 답변! 이를 사용하여 이미지 버튼 드로어 블에 대한 기본 리소스 ID를 포함하므로 프로그래밍 방식으로 확인할 수 있습니다. – NameSpace