7

Cómo usar el botón de evento click en extender baseadapter .. Intenté mucho pero no uso ... En mi proyecto hay una vista de lista personalizada, contiene texto, botón (btnlist), índice de fastscroll . cuando hago clic en el botón (btnlist) no está en otra actividad, no aparece ningún error, no toast ..
Por favor ayúdame con el ejemplo. gracias de antemano.Cómo utilizar el botón onclick en baseAdapter

ref rápida: getView ---> holder.btnList.setOnClickListener

EfficientAdapter.java

public class EfficientAdapter extends BaseAdapter implements SectionIndexer, OnClickListener { 
IndexableListView mListView; 
private String mSections = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
ArrayList<Patient> patientListArray; 

private Intent intent; 
private Patient patient; 
private LayoutInflater mInflater; 
private Context context; 
private int positions; 
ViewHolder holder; 


public EfficientAdapter(Context context) { 
    mInflater = LayoutInflater.from(context); 
    this.context = context; 

    String patientListJson = CountriesList.jsonData; 
    JSONObject jssson; 
    try { 
     jssson = new JSONObject(patientListJson); 
     patientListJson = jssson.getString("PostPatientDetailResult"); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    Gson gson = new Gson(); 
    JsonParser parser = new JsonParser(); 
    JsonArray Jarray = parser.parse(patientListJson).getAsJsonArray(); 
    patientListArray = new ArrayList<Patient>(); 
    for (JsonElement obj : Jarray) { 
     Patient patientList = gson.fromJson(obj, Patient.class); 
     patientListArray.add(patientList); 
    // Log.i("patientList", patientListJson); 

    } 
} 


public int getCount() { 

    return patientListArray.size(); 
} 

public Object getItem(int position) { 

    return position; 
} 

public long getItemId(int position) { 
    return position; 
} 

public View getView(final int position, View convertView, ViewGroup parent) { 

    this.positions = position;  
    View rowView = convertView; 

    if (rowView == null) {      
     LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     rowView = inflater.inflate(R.layout.homemplebrowview, parent, false); 

     holder = new ViewHolder(); 
     holder.text1 = (TextView) rowView.findViewById(R.id.name); 
     holder.text2 = (TextView) rowView.findViewById(R.id.mrn); 
     holder.text3 = (TextView) rowView.findViewById(R.id.date); 
     holder.text4 = (TextView) rowView.findViewById(R.id.age); 
     holder.text5 = (TextView) rowView.findViewById(R.id.gender); 
     holder.text6 = (TextView) rowView.findViewById(R.id.wardno); 
     holder.text7 = (TextView) rowView.findViewById(R.id.roomno); 
     holder.text8 = (TextView) rowView.findViewById(R.id.bedno); 
     holder.btnList = (Button) rowView.findViewById(R.id.listbutton); 
     /*Button editButton = (Button) rowView.findViewById(R.id.listbutton) ; 
     editButton.setTag(position); 
     editButton.setClickable(true); 
     editButton.setOnClickListener(EfficientAdapter.this); 
     rowView.setClickable(true);*/ 


     rowView.setTag(holder); 
    } else { 
     holder = (ViewHolder) rowView.getTag(); 
    } 

    holder.text1.setText(Util.formatN2H(patientListArray.get(position) 
      .getName())); 
    holder.text2.setText(patientListArray.get(position).getMrnNumber()); 
    holder.text3.setText(Util.formatN2H(patientListArray.get(position) 
      .getRoom())); 
    holder.text4.setText(Util.formatN2H(patientListArray.get(position) 
      .getAge())); 
    holder.text5.setText(Util.formatN2H(patientListArray.get(position) 
      .getGender())); 
    holder.text6.setText(Util.formatN2H(patientListArray.get(position) 
      .getWard())); 
    holder.text7.setText(Util.formatN2H(patientListArray.get(position) 
      .getRoom())); 
    holder.text8.setText(Util.formatN2H(patientListArray.get(position) 
      .getBed()));   
    holder.btnList.setOnClickListener(new OnClickListener() { 

     public void onClick(View v) { 
      Toast.makeText(context, "STAT", Toast.LENGTH_SHORT).show();  
      Intent next = new Intent(context, SeviceDetails.class); 
      Log.i("patient", " next "+ position + " onclickposition " + patientListArray.get(position).getMrnNumber()); 
      patient = getPatientDetailsByMrn(patientListArray, position); 
      Log.i("DDDD ", patient.getMrnNumber());    
      next.putExtra("patient", patient); 
      next.putExtra("position", position); 
      System.out.println("patient"+ patient); 
      context.startActivity(next); 
     } 
    }); 
return rowView; 
}  

static class ViewHolder { 
    public Button btnList; 
    public TextView text8; 
    public TextView text7; 
    public TextView text6; 
    public TextView text5; 
    public TextView text4; 
    public TextView text1; 
    public TextView text2; 
    public TextView text3; 
} 

@Override 
public void notifyDataSetChanged() { 
    super.notifyDataSetChanged(); 
} 

public int getPositionForSection(int section) { 
    sortMyData(); 

    Log.i("getPositionForSection", "section" + section); 
    // If there is no item for current section, previous section will be 
    // selected 
    for (int i = section; i >= 0; i--) { 
     for (int j = 0; j < getCount(); j++) { 
      if (i == 0) { 

       Log.i("getPositionForSection- i", "section" + i); 
       // For numeric section 
       for (int k = 0; k <= 9; k++) { 

        if (StringMatcher.match(
          String.valueOf(patientListArray.get(j) 
            .getName().charAt(0)), 
          String.valueOf(k))) 
         Log.i("getPositionForSection- j", "section" + j); 

         return j; 
       } 
      } else { 
       if (StringMatcher.match(
         String.valueOf(patientListArray.get(j).getName() 
           .charAt(0)), 
         String.valueOf(mSections.charAt(i)))) 
        return j; 
      } 
     } 
    } 
    return 0; 
} 

public int getSectionForPosition(int position) { 
    return 0; 
} 

public Object[] getSections() { 
    String[] sections = new String[mSections.length()]; 
    for (int i = 0; i < mSections.length(); i++) 
     sections[i] = String.valueOf(mSections.charAt(i)); 
    return sections; 
} 

/** 
* sorting the patientListArray data 
*/ 
public void sortMyData() { 
    // sorting the patientListArray data 
    Collections.sort(patientListArray, new Comparator<Object>() { 
     @Override 
     public int compare(Object k1, Object k2) { 
      Patient p1 = (Patient) k1; 
      Patient p2 = (Patient) k2; 
      return p1.getName().compareToIgnoreCase(p2.getName()); 
     } 

    }); 
} 


    } 

.xml

<Button 
     android:id="@+id/listbutton" 
     style="?android:attr/buttonStyleSmall" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentRight="true" 
     android:layout_alignTop="@+id/name" 
     android:layout_marginRight="43dp" 
     android:focusable="false"  
     android:text="Episode" 
     android:textColor="#666666" /> 

vista de lista por defecto

 <ListView 

     android:id="@+id/homelistView" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:dividerHeight="0dip" /> 
+0

¿Se selecciona su botón cuando presiona sobre él? – Carnal

+0

El evento @carnel no boss onclick no funciona ... –

+0

Sé que el evento de clic no se activa, pero si el botón no se selecciona, intente configurarlo como enfocable en su archivo xml. – Carnal

Respuesta

6

Debe utilizar el adaptador para llenar la lista con los artículos. Luego, en su Actividad o Fragmento, debe implementar el evento onListItemClick para manejar el clic en el elemento de la lista.

EDIT: Estoy fijando un ejemplo debajo de donde estoy usando un ListFragment - Esta es la parte del código que tengo disponible en este momento, puedo publicar algo específico para ListView más tarde:

public class RecipiesActivity extends FragmentActivity { 

    private RecipiesSummaryListAdapter m_listAdapter; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     /* here you need to set the adapter of the listview 
      and do other things for your applicaiton (i.e. populate the 
      data in your adapter. In your case, since you are calling a 
      WS you want to do that in a different task */ 
     ListFragment lf = 
      (ListFragment) fm.findFragmentById(R.id.my_list_fragment); 
     lf.setListAdapter(m_listAdapter); 
} 

Luego, en su ListFragment:

/* imports and other things go here then... */ 
public class MyListFragment extends ListFragment { 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 

     return (View) inflater.inflate(R.layout.myListViewXml, 
              container, false); 
    } 

    @Override 
    public void onListItemClick(ListView l, View v, int position, long id) { 
     // put your handler here 

    } 
} 

Para más detalles sobre ListFragment ver here.

Creo que un ejemplo muy bueno (aunque extendiendo ArrayAdapter en lugar de BaseAdapter se hown en this stackoverflow answer

hay un punto para recordar:.

  1. El botón no debe ser enfocable (es decir, en XML use android:focusable="false" - como lo tiene en su XML).
  2. Debe capturar proporcionar un evento onItemClick manejado como se muestra a continuación (extraer del enlace anterior):

Código:

listview.setOnItemClickListener(new OnItemClickListener() { 
    //@Override 
    public void onItemClick(AdapterView arg0, View view, 
            int position, long id) { 
     // user clicked a list item, make it "selected" 
     selectedAdapter.setSelectedPosition(position); 
     //Do your stuff here 
} 

Por último, señalar un punto. Esta solución significa que hace clic en la fila de la lista y el evento se dispara.

Creo que si se desea que el usuario haga clic en el botón y el evento de ser despedido en el botón, a continuación, es necesario establecer llamar listview.setItemsCanFocus(true) justo después de inflar el código XML ListView y asegúrese de que el botón es focusable en el XML. Escuchar el evento onClick debería funcionar entonces.

Esto se describe en la diapositiva 25 del mundo GoogleIO de presentación ListView (lo puede conseguir here y la video is here) Esperanza

esto ayuda

+0

seguro ... por favor actualice ... no olvide ... intentaré agregar este código ... gracias por tu respuesta –

+1

Por cierto, si configura 'android: focusable =" false "' para el botón (como lo hizo), al tocar el elemento de la lista se debe activar el evento 'onListItemClick'. Esto debería estar bien, a menos que tenga más de un botón en la fila de la lista. – Lefteris

+0

** actualización (se corrigió el evento) ** Tenga en cuenta que 'onItemSelected' está en el ListView (no en el botón) y que incluirá en la devolución de llamada la posición en la que se hizo clic. Luego use 'getItemAtPosition' para obtener acceso al elemento específico. – Lefteris

2

uso t lo siguiente código en getView() Método:

Button status = (Button) rowView.findViewById(R.id.image1); 
     status.setBackgroundResource(R.drawable.add_account); 
     status.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
         // DO your stuff 
      } 
     }); 
+0

sin necesidad de soporte.botón –

3

pruebe lo siguiente para su botón:

android:focusable="false" 
2

Escriba holder.btnList.setOnClickListener dentro de la condición if (rowView == null) y vuelva a intentarlo.

+0

intenté eso ... pero no uso ... –

Cuestiones relacionadas