Problema de conmutación: solo una opción visible

Quiero usar el conmutador en una aplicación de Android. Lo intenté, pero el principal problema es

  • Si he seleccionado ON, no se mostrará fuera del texto.
  • Si he seleccionado OFF, no se mostrará en el texto.

El texto desactivado no se muestra, pero podemos seleccionar OFF haciendo clic en el área negra del conmutador.

Código

<Switch android:id="@+id/mySwitch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="48dp" android:layout_marginTop="26dp" android:height="50dp" android:text="ON OFF" android:textSize="20sp" android:switchMinWidth="50sp" android:switchPadding="50sp"/> 

En estado

Introduzca aquí la descripción de la imagen

Estado desactivado

Introduzca aquí la descripción de la imagen

¿Cómo puedo mostrar ambos textos al mismo tiempo? ¿Puedo cambiar el texto del conmutador para ambos estados ON / OFF?

Cualquier ayuda sería apreciada.

Gracias por adelantado.

Ir a través de este enlace . Es una buena biblioteca, puedes ir a través del código y averiguar cómo por sí mismo o utilizar la biblioteca como es.

Aquí está mi solución, que crea un widget personalizado para imitar el control Switch. Estoy usando Xamarin, pero este código se puede traducir fácilmente a Java.

SwitchImageView.cs:

 public class SwitchImageView : RelativeLayout { private View view; private bool isChecked; private int imageResourceIdOn = Resource.Drawable.switch_on; private int imageResourceIdOff = Resource.Drawable.switch_off; public SwitchImageView(Context context): base(context) { Init (); } public SwitchImageView(Context context, IAttributeSet attrs) : base(context, attrs) { Init (); } public SwitchImageView(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle) { Init (); } private void Init () { var layoutInflater = (LayoutInflater)ApplicationContext.Activity.GetSystemService (Context.LayoutInflaterService); layoutInflater.Inflate (RPR.Mobile.Resource.Layout.SwitchImageView, this, true); this.Click += (object sender, EventArgs e) => { Checked = !Checked; }; } public int ImageResourceIdOn { get { return imageResourceIdOn; } set { imageResourceIdOn = value; if (isChecked) { this.SetBackgroundResource (value); } } } public int ImageResourceIdOff { get { return imageResourceIdOff; } set { imageResourceIdOff = value; if (!isChecked) { this.SetBackgroundResource (value); } } } public string TextOn { get { return this.FindViewById <TextView> (Resource.Id.switch_on_text).Text; } set { this.FindViewById <TextView> (Resource.Id.switch_on_text).Text = value; } } public string TextOff { get { return this.FindViewById <TextView> (Resource.Id.switch_off_text).Text; } set { this.FindViewById <TextView> (Resource.Id.switch_off_text).Text = value; } } public bool Checked { get { return isChecked; } set { isChecked = value; this.SetBackgroundResource (value ? ImageResourceIdOn : ImageResourceIdOff); this.FindViewById <TextView> (Resource.Id.switch_on_text).SetTextColor (value ? Color.White : Color.Black); this.FindViewById <TextView> (Resource.Id.switch_off_text).SetTextColor (value ? Color.Black : Color.White); if (CheckedChange != null) { CheckedChange (this, value); } } } public event EventHandler<bool> CheckedChange; } 

SwitchImageView.axml:

 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/switch_container" android:layout_width="match_parent" android:layout_height="wrap_content"> <View android:id="@+id/strut" android:layout_width="0dp" android:layout_height="0dp" android:visibility="invisible" android:layout_centerInParent="true" /> <TextView android:id="@+id/switch_off_text" android:layout_width="wrap_content" android:layout_height="match_parent" android:textColor="@color/black" android:text="On" android:textAppearance="?android:attr/textAppearanceSmall" android:paddingLeft="10dp" android:paddingTop="3dp" /> <TextView android:id="@+id/switch_on_text" android:layout_toRightOf="@+id/strut" android:layout_width="wrap_content" android:layout_height="match_parent" android:textColor="@color/white" android:text="Off" android:textAppearance="?android:attr/textAppearanceSmall" android:paddingRight="5dp" android:paddingLeft="10dp" android:paddingTop="3dp" /> </RelativeLayout> 

Hay uno hecho por 2 botones estándar y un LinearLayout. Hay un montón de archivos xml para importar, pero funciona perfecto en todas las versiones y muy fácil de usar. Compruebe la siguiente página de Github

Avance

Interruptor de encargo con 2 botones

uso

  1. Copie los archivos XML en res / drawable a la carpeta res / drawable de su proyecto.
  2. Copie LinearLayout de layout.xml en su archivo de diseño.
  3. Copie valores de valores / colors.xml y values ​​/ dimens a sus propios archivos.
  4. Initilize el interruptor con el siguiente código

SekizbitSwitch mySwitch = new SekizbitSwitch(findViewById(R.id.sekizbit_switch)); mySwitch.setOnChangeListener(new SekizbitSwitch.OnSelectedChangeListener() { @Override public void OnSelectedChange(SekizbitSwitch sender) { if(sender.getCheckedIndex() ==0 ) { System.out.println("Left Button Selected"); } else if(sender.getCheckedIndex() ==1 ) { System.out.println("Right Button Selected"); } } });

  • ¿Reutilizar las actividades anteriores?
  • ¿O declaración en el interruptor / caso?
  • Interruptor multinivel Android
  • Cómo cambiar el color de entrada del imput en xml?
  • Cambiar las actividades de un lado a otro en Android
  • ¿Por qué utilizar un hashmap?
  • Menú emergente personalizado de Android con conmutador
  • Ocultar texto predeterminado para el botón de Android
  • Cobertura de Jacoco para la declaración de switch
  • Cómo cambiar entre actividades con viewflipper
  • Android: El botón OnClickListener no funciona
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.