2011-02-19 2 views
9

안드로이드, XML의 체크 박스 리스너?

XML :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
       android:orientation="vertical" 
       android:layout_width="match_parent" 
       android:layout_height="match_parent"> 
    <Button android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:id="@+id/addContactButton" 
       android:text="@string/addContactButtonLabel" 
       android:onClick="launchContactAdder"/><!-- here --> 

</LinearLayout> 

Java :

public void launchContactAdder(View v) 
{ 
    Intent i = new Intent(this, ContactAdder.class); 
    startActivity(i); 
} 
그러나 메소드가 public, void 및 가장 중요한 take가되어야한다는 요구 사항이 있습니다. 인수로보기.

이제 똑같은 일을하고 싶지만 체크 박스 버튼을 쓰고 싶습니다. Checkbox에는 android : onclick 속성이 있지만 Android 튜토리얼 (http://developer.android.com/resources/samples/ContactManager/index.html)에서이 코드를 볼 수 있습니다.

showInvisibleControl.setOnCheckedChangeListener(new OnCheckedChangeListener() 
{ 
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) 
    { 
     Log.d(TAG, "mShowInvisibleControl changed: " + isChecked); 
     showInvisible = isChecked; 
     populateContactList(); 
    } 
}); 

따라서 onCheckedChanged CompoundButton buttonView, boolean isChecked) 메소드를 호출합니다. XML로이 작업을 수행 할 수있는 방법이 있습니까? android : onCheckedChange 속성은 없으며 android : onClick 속성 만 있지만 위에서 쓴 것처럼 해당 속성의 이름은 View를 인수로 취하는 해당 메소드 이름을 가져야합니다. 위의 코드에서 메소드가 있어야한다는 것을 알고 있습니다. CompoundButton 및 boolean 인수.

"XML 방식"으로 할 수있는 방법은 없나요?

답변

4

Spinner 위젯의 onItemSelected 이벤트에서 비슷한 문제가 발견되었습니다. 외관상으로는 안드로이드 팀은 충분히 onClick 이벤트를 XML로 보냈다 고 생각했습니다.

6

공식 문서 : https://developer.android.com/guide/topics/ui/controls/checkbox.html

<CheckBox android:id="@+id/checkbox_meat" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/meat" 
    android:onClick="onCheckboxClicked"/> 
<CheckBox android:id="@+id/checkbox_cheese" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/cheese" 
    android:onClick="onCheckboxClicked"/> 
2

이 라이브러리에 데이터 바인딩을 사용하여이 작업을 수행 할 수있게되었습니다. 먼저 핸들러 클래스를 만들어야합니다 (이 예제에서는 MainActivityHandlers라고 부릅니다). 이 핸들러 클래스 내부 레이아웃 파일에 다음의 해당 구현 있는 방법 (예를 들어 이름이 방법 항목이다) 정의, 당신은 단지 구현해야합니다

... 
<data> 
    <variable 
     name="handler" 
     type="com.test.android.testapp.MainActivityHandlers" /> 
</data> 
... 
     <RadioGroup 
     ... 
     android:onCheckedChanged="@{handler.method1}" 
     ... 
     > 

을 당신은 갈 수 있어요. 추가 정보 : https://developer.android.com/topic/libraries/data-binding/index.html