(Android) Initialize a view object in a Button and ImageButton

0

Good morning!

I open this topic in case you can help me. It turns out that I have to create an object that inherits from View, but depending on a value it must be either a Button or an ImageButton. The problem is that I tried casting and directly creating the button or the imagebutton and nothing. The code that I attached is what I have now. The fact is that I do not know how to move from a View to Button or ImageButton, since these two elements are View.

After the modifications, I want to clarify that I would like to know how, a class that inherits from View, can become a Button or an ImageButton, since with inheritance it arrives, only that.

Class box

public class Casilla extends View{

private int contenido;

public Casilla(Context context) {
    super(context);
}

public int getContenido() {
    return contenido;
}

public void setContenido(int contenido) {
    this.contenido = contenido;
}

}

Tablero Class (fillTablero method)

private void llenarTablero() {
    for(int i=0;i<8;i++){
        for(int j=0;j<8;i++){
            if(matriz[i][j]==-1){
                casillas[i][j]= new Casilla(context);
            }
            else{
                casillas[i][j]= new Casilla(context);

            }
        }
    }
}

From what I remember that I have tried, I have done this, which is what I thought would work.

private void llenarTablero() {
    for(int i=0;i<8;i++){
        for(int j=0;j<8;i++){
            if(matriz[i][j]==-1){
                //casillas[i][j]=new ImageButton(context);
                casillas[i][j]= (ImageButton)new Casilla(context);
            }
            else{
                //casillas[i][j]=new Button(context);
                casillas[i][j]= (Button)new Casilla(context);

            }
        }
    }
}

Greetings and thank you very much for the answers.

    
asked by Carlos Bustos 13.11.2017 в 11:51
source

1 answer

1

Your instance is badly created, try something like this:

Casilla boton = new Casilla(this);
Button btn = (Button) boton;

Casilla imageBoton = new Casilla(this);
ImageButton iBtn = (ImageButton) imageBoton;
    
answered by 13.11.2017 в 19:25