在Android中,切换按钮不显示ON和OFF文本

我正在以编程方式创建一个切换按钮。 我遇到的问题是该按钮不显示ON / OFF文本。 这是创建代码:

  final RelativeLayout.LayoutParams ll = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); ll.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); sw.setLayoutParams(ll); sw.setTextOn(values[0].getName()); sw.setTextOff(values[1].getName()); values[0].getName() returns "OK", and values[1].getName() returns "NOK" 

可能会发生什么?

谢谢Jaime

您可以通过XML执行此操作

  

或者以编程方式

 mSwitch.setShowText(true); 

以下是Android-API的答案。 你必须标记它可以显示标签的开关!!

public void setShowText(boolean showText)在API级别21中添加

设置是否应显示开/关文本。

相关的XML属性:

 android:showText 

参数showText true显示开/关文本

http://developer.android.com/reference/android/widget/Switch.html#setShowText%28boolean%29

希望这会有所帮助

     

MainActivity.java

 import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.Switch; import android.widget.TextView; public class MainActivity extends Activity { private TextView switchStatus; private Switch mySwitch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); switchStatus = (TextView) findViewById(R.id.switchStatus); mySwitch = (Switch) findViewById(R.id.mySwitch); //set the switch to ON mySwitch.setChecked(true); //attach a listener to check for changes in state mySwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked){ switchStatus.setText("Switch is currently ON"); }else{ switchStatus.setText("Switch is currently OFF"); } } }); //check the current state before we display the screen if(mySwitch.isChecked()){ switchStatus.setText("Switch is currently ON"); } else { switchStatus.setText("Switch is currently OFF"); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }