2

我試圖更改Android中切換按鈕的默認開啓和關閉文本。我知道如何在XML中做到這一點。我的查詢是如何在代碼中以編程方式實現。在Android中以編程方式實現「android:textOff」&「android:textOn」屬性切換按鈕

任何人都可以請指教?非常感謝。

+0

任何更多的建議,請任何人?? – user788511

+1

嘗試此操作的最佳方法是: ToggleButton btn = new ToggleButton(this); btn.setTextOn(string value); btn.setTextOff(string value); – user788511

回答

3

使用ToggleButton.setTextOn(String)ToggleButton.setTextOff(String)

1

您可以在切換按鈕設置開/關在XML像下面的Java代碼切換按鈕

<ToggleButton 
      android:id="@+id/toggBtn" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_centerVertical="true" 
      android:layout_alignParentRight="true" 
      android:gravity="center" 
      android:textOn="On"   //when your button on by clicking "On" text will be displayed 
      android:textOff="Off" /> //When you off the toggle button "Off" text will be displayed 

// XML代碼。

ToggleButton toggleButton=(ToggleButton)findViewById(R.id.toggBtn); 

toggleButton.setOnClickListener(new OnClickListener(){ 
      @Override 
      public void onClick(View arg0) { 
       if(toggleButton.getText().toString().equals("on")){ 
       ////do when toggle button is on 
       }else if(toggleButton.getText().toString().equals("off")){ 
       // do when toggle button is off 
       } 

      } 
     }); 
+0

llango請你澄清一些,最好用一些代碼?謝謝 – user788511

1

你可以嘗試這樣的事情:

ToggleButton btn = new ToggleButton(this); //this is optional and you should use your way to create the button :) 
    if (btn.isChecked()) 
    { 
     btn.setText("something"); 
    } 
    else 
    { 
     btn.setText("something else"); 
    } 

忠告:你應該把此驗證在onclickListener :)

+0

謝謝Arkde,但是這似乎不工作..值保持不變 – user788511

相關問題