Java – Public methods of View objects cannot be accessed in Java (Android)

Public methods of View objects cannot be accessed in Java (Android)… here is a solution to the problem.

Public methods of View objects cannot be accessed in Java (Android)

This seems like a basic issue, so I’m sure this is a minor issue I’ve overlooked. Maybe I just watched it for too long.

I’ve been trying to create an onClick listener in View, and I have a public setup method to set up the listener. However, when I try to call the method outside the class, I get an error message saying that it cannot resolve the method.

I’ve tried creating other public methods or public member variables, but for some reason I can’t view any of them outside of the class.

Here are some related fragments:

PaintView: (I can’t get the class of the public member from).

public class PaintView extends View {
    public interface OnPaintClickedListener
    {
        public void onPaintClicked(int color);
    }
    private OnPaintClickedListener _onPaintClickedListener;

public void setOnPaintClickedListener(OnPaintClickedListener listener)
    {
        _onPaintClickedListener = listener;
    }
...
}

PaletteView: (class that uses PaintView).

public class PaletteView extends ViewGroup {
....
    public void addColor(Context context, int color)
    {
        View newPaintView = new PaintView(context, color);

setOnPaintClickedListener gives the message "Cannot resolve method setOn... blah blah'
        newPaintView.setOnPaintClickedListener(new PaintView.OnPaintClickedListener()
        {
            @Override
            public void onPaintClicked(int color)
            {

}
        });
        this.addView(newPaintView);
    }
}

The interface code is fine, that is, you can find the setOnPaintClickedListener method.

Thanks in advance, I’m 97% sure I’ll feel like an idiot once someone points out my mistake.

Solution

Change to:

<strong>PaintView</strong> newPaintView = new PaintView(context, color);

Interpretation… Because the variable you are using is declared with the View type, the compiler cannot find the method defined in the subclass PaintView, so it prompts.

Alternatively, you

can keep the same declaration, and when calling a particular method, you have to convert to a subclass like this:

(

(<strong>PaintView</strong>)newPaintView).setOnPaintClickedListener

Related Problems and Solutions