In DialogFragment, it gives an error if I specify android in onload: onclick = "onClickCancel" and, from where the dialog fragment is called, I create a method

public void onClickCancel(View view){ dlg1.dismiss(); log("onlcickcancel"); } 

when I click it gives an error

  java.lang.IllegalStateException: Could not find a method onClickCancel(View) in the activity class android.view.ContextThemeWrapper for onClick handler on view class android.widget.Button with id 'button5' 

wrote in a fragment

  view.findViewById(R.id.button6).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); Log.i("fr", "dismiss"); } }); 

and he doesn't even react, what am I doing wrong.

Now I write like this

 public class AddCommentFragment extends DialogFragment implements View.OnClickListener 

......

  View view = inflater.inflate(R.layout.fragment_add_comment, null); view.findViewById(R.id.button5).setOnClickListener(this); ...... @Override public void onClick(View v) { dismiss(); switch (v.getId()) { case R.id.button6: dismiss(); break; default: break; } } 

doesn't react too

I call a fragment in the activation df.show ();

xml buttons

 <EditText android:layout_width="match_parent" android:layout_margin="10dp" android:hint="Введите сюда ваш комент" android:layout_height="wrap_content" android:id="@+id/editText4" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Cancel" android:layout_margin="10dp" android:id="@+id/button6" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="OK" android:layout_margin="10dp" android:id="@+id/button5" android:layout_alignParentTop="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" /> </RelativeLayout> 

    2 answers 2

    Try this: add the implementation of the OnClickListener interface in the class definition

     public class Dialog1 extends DialogFragment implements OnClickListener 

    remove android: onclick = "onClickCancel" property in layout'e, but add id:

     android:id="@+id/btn1" 

    in an OnCreateView type like this:

     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.dialog1, null); v.findViewById(R.id.btn1).setOnClickListener(this); return v; } 

    and then onclick:

     public void onClick(View v) { switch (v.getId()) { case R.id.btn1: dismiss(); break; default: break; } } 

      Probably because in xml:

       android:onclick="cancelClick", 

      and in the code:

       public void onClickCancel. 
      • no, I wrote it manually here, now I will correct it - J Mas
      • Then xml to studio - Igor Viskov