Ben Mustapha Sabrine Ben Mustapha Sabrine - 1 month ago 9
Android Question

how can I add a listener on the buttons of a fragment in android

i am trying to display a pop up when i click on an item view.
when the pop up is open the buttons doesn't work.
here is my onItemClick function :

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
this.id = position;
alert.setTitle("Alert");
alert.setMessage("Souhaitez-vous modifier ou supprimer?");
alert.setView(R.layout.alert_view);

LayoutInflater inflater= LayoutInflater.from(this);
layoutAlert=(LinearLayout)inflater.inflate(R.layout.alert_view,null);

btn_supp = (Button)layoutAlert.findViewById(R.id.btn_supp_alert);
btn_modif = (Button)layoutAlert.findViewById(R.id.btn_modifier_alert);
ed_nom = (EditText)layoutAlert.findViewById(R.id.ed_nom_alert);
ed_prenom = (EditText)layoutAlert.findViewById(R.id.ed_prenom_alert);
ed_tel = (EditText)layoutAlert.findViewById(R.id.ed_tel_alert);
System.out.println(Principal.mesContacts.get(position).getNom().toString());
ed_nom.setText(Principal.mesContacts.get(position).getNom().toString());
btn_supp.setOnClickListener(this);
btn_modif.setOnClickListener(this);
alert.show();
}


and this is my onClick function:

public void onClick(View v) {

if(v==btn_supp)
{
Principal.mesContacts.remove(id);
listView.invalidateViews();

}
if(v==btn_modif)
{
Principal.mesContacts.set(id,new Contact(ed_nom.getText().toString(),ed_prenom.getText().toString(),ed_tel
.getText().toString()));
listView.invalidateViews();
}
}


but that doesn't work, I don't know why

Answer

Okay what you basically did is the following:

alert.setView(R.layout.alert_view);:

With this line of code, you instruct the AlertDialog.Builder class to inflate a new layout from the specified resource R.layout.alert_view and set it as the layout of the AlertDialog.

With the following lines of code you inflated a new layout of the same resource. For this instance you set the OnClickListener. But your constructed layout never got set to the AlertDialog.Builder object.

So the AlertDialog.Builder wasn't aware of your layout and used the layout specified by alert.setView(R.layout.alert_view);. Does that make it clear to you?

Comments