2011-12-29 29 views

Trả lời

162

Bạn có thể sử dụng sau đây để thiết lập các văn bản từ mã:

toggleButton.setText(textOff); 
// Sets the text for when the button is first created. 

toggleButton.setTextOff(textOff); 
// Sets the text for when the button is not in the checked state. 

toggleButton.setTextOn(textOn); 
// Sets the text for when the button is in the checked state. 

Để thiết lập các văn bản sử dụng xml, sử dụng như sau:

android:textOff="The text for the button when it is not checked." 
android:textOn="The text for the button when it is checked." 

Thông tin này là từ here

+1

tuy nhiên nó không hoạt động trên e.i. samsung và điện thoại htc – Serafins

+2

Serafins, điều đó không đúng. Nó hoạt động trên điện thoại Samsung và HTC. – interrupt

+3

Khi cập nhật văn bản bật và tắt theo chương trình, nút không tự vẽ lại bằng văn bản mới. Bạn có thể buộc vẽ lại bằng cách gọi setChecked (toggleButton.isChecked). Nghe có vẻ vô lý nhưng đó là một hack để buộc vẽ lại. Xem [câu trả lời stackoverflow này] (http://stackoverflow.com/a/3792554/2590478). – MidasLefko

14

Trong ví dụ bạn liên kết đến, chúng sẽ thay đổi thành Ngày/Đêm bằng cách sử dụng android:textOnandroid:textOff

+0

Tôi thực sự liên kết với một câu hỏi khác mà tôi chưa bao giờ thấy trước đây. Cảm ơn bạn đã chỉ ra câu trả lời trong câu hỏi của riêng tôi. – styler1972

6

Đặt XML như:

<ToggleButton 
    android:id="@+id/flashlightButton" 
    style="@style/Button" 
    android:layout_above="@+id/buttonStrobeLight" 
    android:layout_marginBottom="20dp" 
    android:onClick="onToggleClicked" 
    android:text="ToggleButton" 
    android:textOn="Light ON" 
    android:textOff="Light OFF" /> 
1

Có vẻ bạn không còn cần toggleButton.setTextOff (textOff); và toggleButton.setTextOn (textOn) ;. Văn bản cho mỗi trạng thái được chuyển đổi sẽ thay đổi bằng cách chỉ bao gồm các đặc tính xml có liên quan. Thao tác này sẽ ghi đè văn bản BẬT/TẮT mặc định.

<ToggleButton 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/toggleText" 
    android:textOff="ADD TEXT" 
    android:textOn="CLOSE TEXT" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="10dp" 
    android:visibility="gone"/> 
Các vấn đề liên quan