Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NoSuchMethodException: onClick in Fragment

Tags:

android

Just wandering why the next code comes up with a "NoSuchMethodException: onPrefImageClick [class android.view.View]" message.

    public View onCreateView(LayoutInflater inflater,
                         ViewGroup container,
                         Bundle savedInstanceState)
{
    View mView = inflater.inflate(R.layout.pref_detail_fragment, container, false);

    return mView;
}   // onCreateView()


public void onPrefImageClick(final View clickedView)
{
    switch(clickedView.getId())
    {
    case R.id.prefDetailImage:
        Log.i(TAG, "Clicked on the image");
        break;
    case R.id.prefDetailText:
        Log.i(TAG, "Clicked on the text");
        break;
    default:
        Log.i(TAG, "Clicked some where");
    }
}   // onPrefImageClick()

with

               android:onClick="onPrefImageClick"

present in the xml.

And this code:

    @Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container,
                         Bundle savedInstanceState)
{
    View mView = inflater.inflate(R.layout.pref_detail_fragment, container, false);


    final ImageView imgView = (ImageView) mView.findViewById(R.id.prefDetailImage);
    imgView.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.i(TAG, "Clicked on the image");
            // Perform action on click
        }
    });

    return mView;
}   // onCreateView()

While with both the line from xml and the onPrefImageClick() method removed;

works just fine.

Can / will someone explain please?

like image 398
PageMaker Avatar asked Feb 02 '26 08:02

PageMaker


1 Answers

You should put the onPrefImageClick in the Activity which hosts the Fragments. This is because, Android will look for the method in the Activity not in the Fragment. Android doesn't know for sure, which Fragment is currently up and hence it looks in the Activity.

like image 128
Levente Kurusa Avatar answered Feb 04 '26 23:02

Levente Kurusa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!