RU92Z RU92Z - 1 month ago 16
Android Question

Issue with onClickListener for Button in Fragment

I have a button in a fragment class that I'd like to have trigger a method in the parent activity. I've implemented an interface for this.

My issue is that the View.onClickListener is giving me the following error:


Class 'Anonymous class derived from onClickListener' must either be declared abstract or implement abstract method 'onClick(View)' in 'onClickListener'


Which is odd, because I'm implementing onClick(View).

Here is the code in my Fragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(com.zlaporta.chessgame.R.layout.gamedescfragment, container, false);
final Button make_move = (Button) v.findViewById(R.id.make_move);
make_move.setOnClickListener(new ***View.OnClickListener()*** {
public void OnClick(View v) {
makeMoveCallback.makeMoveMethod();
}
});


The stars indicate the portion of the code that Android Studio doesn't like.

Answer

Do it using Anonymous inner class in an object:

//declaring OnClickListener as an object
private OnClickListener btnClick = new OnClickListener() {
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }
};

//passing listener object to button
make_move.setOnClickListener(btnClick);

Hope this will help :)

Comments