Skip to content Skip to sidebar Skip to footer

Android Dialogfragment Android:onclick="buttoncancel" Causes Illegalstateexception Could Not Find A Method

I have a problem with my Dialog Fragment. I wanted to use android:onClick attribute as in my opinion code is more clear then. In my layout I have the following declaration:

Solution 1:

I would try a different approach which works fine for me:

  1. implement an OnClickListener into your fragment:

    publicclassDialogNewDatabaseextendsDialogFragmentimplementsOnClickListener`
    
  2. have a button with an unique id in xml, which does NOT need android:clickable

    <Button  android:id="@+id/dialog_new_database_button_cancel" />
    
  3. override the method onClick() within your fragment and insert a reaction on your click:

    publicvoidonClick(View v){       
      switch (v.getId()) {
        case R.id.dialog_new_database_button_cancel:
            // your stuff herethis.dismiss();
    
            break;          
        default:                
            break;
       }
    }   
    
  4. import the necessary:

    import android.view.View.OnClickListener; 
    
  5. start the onClickListener on the button:

    privateButtonbCancel=null;
    bCancel = (Button) findViewById(R.id.dialog_new_database_button_cancel);
    bCancel.setOnClickListener(this);
    // it is possible that you might need the refrence to the view.// replace 2nd line with (Button) getView().findViewById(...);

    This way you can handle even more clickable buttons in the same onClick-method. You just need to add more cases with the proper ids of your clickable widgets.

Solution 2:

I don't think that is related to the support fragment.

The issue seems to arise from the fact that you are registering a onClick on XML that fires up based on the activity that the fragment was binded at the time of the click.

As your "buttonCancel" method does not exists in the activity (because it is inside the fragment), it fails.

I don't think that really is a desirable solution, but you can register your "buttonCancel" method on your activity for that error to go away, and make that "buttonCancel" method registered on the activity only call the method that exists in the fragment, in case you want to keep your action / view behaviour inside the fragment.

Solution 3:

Try:

@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView (inflater, container, savedInstanceState);
    Viewview= inflater.inflate(R.layout.dialog_new_database, container);    
    getDialog().setTitle("Hello");
    return view;

    privatevoidbuttonCancel(View view) {
    dismiss();
    }
    privatevoidbuttonOK(View view) {
    }
}

Post a Comment for "Android Dialogfragment Android:onclick="buttoncancel" Causes Illegalstateexception Could Not Find A Method"