2011-03-26 9 views
9

Todos mis otros métodos onClick funcionan, excepto los en los que tengo que inflar el diseño para obtener el botón. ¡Qué estoy haciendo mal! Aquí hay un código:Botones de diseño inflado onClick listener no funciona

package com.games.think; 

import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 

import android.app.Activity; 
import android.content.Context; 
import android.os.Bundle; 
import android.view.LayoutInflater; 
import android.view.View; 

import android.widget.Button; 
import android.widget.RadioButton; 
import android.widget.TableLayout; 

public class Think extends Activity{ 
    //What question are we on? 
    int question = 1; 
    //What level are we on? 
    String lvl ="1"; 

    //Radio buttons we need to access them global 
    RadioButton lvl1; 
    RadioButton lvl2; 
    RadioButton lvl3; 
    RadioButton lvl4; 
    RadioButton lvl5; 

    /** Called when the activity is first created. */ 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     //play 
     Button play = (Button)findViewById(R.id.play); 
     play.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       playOnClick(v); 

      } 
     }); 
     //level 
     Button level = (Button)findViewById(R.id.level); 
     level.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       levelOnClick(v); 

      } 
     }); 

     //setLevel 
     LayoutInflater inflater = LayoutInflater.from(this); 
     TableLayout tbl = new TableLayout(this); 

     View playv = inflater.inflate(R.layout.level, null); 
     Button updateLevel = (Button) playv.findViewById(R.id.updateLevel); 
     tbl.addView(updateLevel); 

     updateLevel.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        updateLevelOnClick(v); 
       } 
      }); 

     View levelv = inflater.inflate(R.layout.play, null); 
     Button gotomenu = (Button) levelv.findViewById(R.id.tomenu); 

     gotomenu.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        toMenuOnClick(v); 
       } 
      }); 





     //Radio Buttons 
     lvl1 = (RadioButton) levelv.findViewById(R.id.lvl1); 

     lvl2 = (RadioButton) levelv.findViewById(R.id.lvl2); 

     lvl3 = (RadioButton) levelv.findViewById(R.id.lvl3); 

     lvl4 = (RadioButton) levelv.findViewById(R.id.lvl4); 

     lvl5 = (RadioButton) levelv.findViewById(R.id.lvl5); 
     //tomenu 


     lvl = getLevel(); 


     if(lvl.equals("-1")) { 
      lvl=getLevel(); 

     } 






    } 




    protected void toMenuOnClick(View v) { 
     setContentView(R.layout.main); 

    } 




    protected void updateLevelOnClick(View v) { 

     setContentView(R.layout.main); 


    } 




    protected void levelOnClick(View v) { 
     setContentView(R.layout.level); 


     if(lvl.equals("1")) { 
      lvl1.setChecked(true); 
     } 
     if(lvl.equals("2")) { 
      lvl2.setChecked(true); 
     } 
     if(lvl.equals("3")) { 
      lvl3.setChecked(true); 
     } 
     if(lvl.equals("4")) { 
      lvl4.setChecked(true); 
     } 
     if(lvl.equals("5")) { 
      lvl5.setChecked(true); 
     } 

    } 




    protected void playOnClick(View v) { 
     setContentView(R.layout.play); 


     setQuestion(); 


    } 






    private String getLevel() { 

     String FILENAME = "think_level"; 
     FileInputStream fis; 
     byte[] buffer = new byte[1000]; 


     try { 
      fis = openFileInput(FILENAME); 
     } catch (FileNotFoundException e) { 
      setLevel("1"); 
      return "-1"; 
     } 

     try { 
      fis.read(buffer,0,1000); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     try { 
      fis.close(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     String level = buffer.toString(); 

     return level; 
    } 

    private void setLevel(String _level) { 
     String FILENAME = "think_level"; 
     String level = _level; 

     FileOutputStream fos; 
     try { 
      fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); 
      fos.write(level.getBytes()); 
      fos.close(); 
     } catch (Exception e) { 

      e.printStackTrace(); 

     } 

    } 

    private void setQuestion() { 




    } 



    } 

Éstos son mis archivos xml: Main.xml:

<?xml version="1.0" encoding="utf-8"?> 

    <TableLayout android:id="@+id/tableLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"> 
     <ImageView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/imageView1" android:src="@drawable/think" android:scaleType="fitCenter"></ImageView> 
     <Button android:id="@+id/play" android:text="Play" android:layout_height="wrap_content" android:layout_width="wrap_content" ></Button> 
     <Button android:text="Level" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/level"></Button> 


    </TableLayout> 

aquí es mi level.xml

<?xml version="1.0" encoding="utf-8"?> 
    <TableLayout android:id="@+id/tableLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"> 
     <TableRow android:id="@+id/tableRow1" android:layout_width="wrap_content" android:layout_height="wrap_content"> 
      <TextView android:text="Level:" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView> 
     </TableRow> 
     <TableRow android:id="@+id/tableRow2" android:layout_width="wrap_content" android:layout_height="wrap_content"> 
      <RadioGroup android:id="@+id/radioGroup1" android:layout_width="wrap_content" android:layout_height="wrap_content"> 
       <RadioButton android:id="@+id/lvl1" android:text="Level 1" android:layout_height="wrap_content" android:checked="true" android:layout_width="wrap_content"></RadioButton> 
       <RadioButton android:id="@+id/lvl2" android:text="Level 2" android:layout_height="wrap_content" android:layout_width="wrap_content"></RadioButton> 
       <RadioButton android:id="@+id/lvl3" android:text="Level 3" android:layout_height="wrap_content" android:layout_width="wrap_content"></RadioButton> 
       <RadioButton android:id="@+id/lvl4" android:text="Level 4" android:layout_height="wrap_content" android:layout_width="wrap_content"></RadioButton> 
       <RadioButton android:id="@+id/lvl5" android:text="Level 5" android:layout_height="wrap_content" android:layout_width="wrap_content"></RadioButton> 
      </RadioGroup> 
     </TableRow> 
     <Button android:text="Set Level" android:id="@+id/updateLevel" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> 
    </TableLayout> 

aquí es play.xml:

<?xml version="1.0" encoding="utf-8"?> 
<TableLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    <ScrollView android:id="@+id/scrollView1" android:layout_width="wrap_content" android:layout_height="wrap_content"> 
     <TextView android:text="TextView" android:id="@+id/question" android:layout_height="wrap_content" android:layout_width="wrap_content"></TextView> 
    </ScrollView> 
    <RadioGroup android:id="@+id/radioGroup1" android:layout_width="wrap_content" android:layout_height="wrap_content" > 
     <RadioButton android:id="@+id/radioButton1" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="RadioButton"></RadioButton> 
     <RadioButton android:id="@+id/radioButton2" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="RadioButton"></RadioButton> 
     <RadioButton android:id="@+id/radioButton3" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="RadioButton"></RadioButton> 
    </RadioGroup> 
    <Button android:id="@+id/go" android:text="Go" android:layout_height="wrap_content" android:layout_width="wrap_content"></Button> 
    <Button android:id="@+id/tomenu" android:text="Back To Menu" android:layout_height="wrap_content" android:layout_width="wrap_content"></Button> 
</TableLayout> 
+1

¿Seguro de su adición a los botones de la pantalla? –

+0

No están en el diseño main.xml, sino en otros diseños. Sí, estoy seguro de que están en la pantalla porque puedo acceder a las pantallas level.xml y play.xml pero no a la anterior porque el escucha onclick no funciona. –

Respuesta

19

El problema es que la vista que está agregando no tiene un elemento principal y, por lo tanto, no puede recibir eventos de clic. Actualmente está inflando la vista usando

View playv = inflater.inflate(R.layout.level, null); 

Le conviene colocar una vista principal en ese segundo argumento.

View playv = inflater.inflate(R.layout.level, parentView, false); 

Esto le permitirá usar una vista primaria pero no adjuntarla.

+0

¿Debo obtener el grupo de vista principal del archivo level.xml y agregar el grupo de vista principal como segundo argumento? –

+0

He actualizado mi pregunta –

+0

Utilizará la vista a la que desee agregar su vista inflada. –

0

No hay appar razón por la cual esto no debería funcionar.

Cualquier tiempo de ejecución vistas creadas se deben agregar a su LinearLayout (o cualquier otra disposición de los padres) usando:

linearLayoutMain.addView(updateLevel); 

¿Ha utilizado este botones en cualquiera de los diseños lineales en su decir, el archivo XML hace estos botones aparece cuando alcanzas la actividad correspondiente?

+0

Además, no entendí lo que quería decir con "Puedo acceder a las pantallas level.xml y play.xml". Pensé que estás usando estos xmls para inflar los botones. Entonces, ¿los estás usando en cualquier otra actividad? –

+0

El diseño level.xml y play.xml son en realidad diseños que tienen botones e imágenes de padres. –

1

Por lo tanto, los botones están en su nivel y en los diseños de juego, y está inflando esos diseños, pero no parece que vaya a agregar los diseños a su vista/diseño principal. ¿De verdad puedes ver esos dos diseños que estás inflando?

+0

En mi diseño main.xml, ¡tengo dos botones para jugar y nivelar! Cuando hago clic en play me lleva al play.xml y veo todo bien y lo mismo con el botón de nivel. Pero el oyente onclick no funciona, ¿cómo soluciono esto? –

+0

Bien ... ¿está seguro de que no es un problema con las funciones setLevelOnClick yMenuOnClick? ¿Puedes publicar el código para ellos? – BigFwoosh

+0

publicó todo el archivo java –

0

Debería estar viendo la excepción en tbl.addView(updateLevel);, porque está intentando agregar una vista cuyo elemento primario ya está especificado.

¿No está viendo esta excepción?

+0

No, no veo ninguna excepción –

+0

Por favor revise su código publicado, utilicé el mismo código y estoy viendo esta excepción. – Karan

0

la inflación es el método asíncrono, se puede tratar de añadir el detector de clics después de su inflado

//only inflate in oncreate/onresume 
    inflater.inflate(
      R.layout.play, // resource 
      this,    // root 
      true); //attach to root 

//overide onFinishInflate and get the view here 
    protected void onFinishInflate() { 
    super.onFinishInflate(); 
    Button gotomenu = (Button) levelv.findViewById(R.id.tomenu); 

    gotomenu.setOnClickListener(new View.OnClickListener() { 
     @Override 
      public void onClick(View v) { 
      toMenuOnClick(v); 
      } 
     }); 
    } 
0

Si Usted desea valor del artículo sobre el tema clic sólo tiene que utilizar .setTag (un valor); y getTag();

RelativeLayout firstContactRlayout = (RelativeLayout) myLayout.findViewById(R.id.firstContactRlayout); 
    firstContactRlayout.setTag(number); 
    firstContactRlayout.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      String gettags = (String) v.getTag(); 
      Log.e("gettags", "--" + gettags); 
     } 
    }); 
0

Prueba esto después tbl.addView(updateLevel); 0 de tbl.getChildAt(0) puede cambiar:

tbl.getChildAt(0).findViewById(R.id.updateLevel).setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     updateLevelOnClick(v); 
    } 
}); 
Cuestiones relacionadas