AndroidStudio onCheackedChangeListener

galarga

New Member
#1
Quiero aprender a usar el escuchador onCheackedChangeListener, pero cada vez que lo quiero implementar se cierra la app, se que se puede hacer con onCLick, pero necesito saber usar este

Google Translate:
I want to learn how to use the listener onCheckedChangeListener, but every time I want to implement it, the app is closed, I know it can be done with onCLick, but I need to know how to use this:
Mã:
package com.example.tonij.colores;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    CheckBox rojo,verde,azul;
    Button ponerColor, borrar;
TextView texto;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        rojo= (CheckBox) findViewById(R.id.botonRojo);
        verde= (CheckBox) findViewById(R.id.botonVerde);
        azul= (CheckBox) findViewById(R.id.botonAzul);

        rojo.setOnCheckedChangeListener(
                new CheckBox.OnCheckedChangeListener(){
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if(isChecked==true){
                            texto.setText("enga");
                        }
                    }
                }
        );

        ponerColor= (Button) findViewById(R.id.ponerColor);
        borrar= (Button) findViewById(R.id.borrar);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
 

Admin

Administrator
Thành viên BQT
#2
You are declaring those widgets before onCreate() method perhaps that causes the issue. However, you never initialized the TextView (texto) too.

So try this:
Mã:
@Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
        final TextView texto = (TextView) findViewById(R.id.yourTextviewid);
        ponerColor= (Button) findViewById(R.id.ponerColor);
        borrar= (Button) findViewById(R.id.borrar);
        rojo= (CheckBox) findViewById(R.id.botonRojo);
        verde= (CheckBox) findViewById(R.id.botonVerde);
        azul= (CheckBox) findViewById(R.id.botonAzul);

        rojo.setOnCheckedChangeListener(
                new CheckBox.OnCheckedChangeListener(){
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if(isChecked){
                            texto.setText("enga");
                        }
                    }
                }
        );

}
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top