JAAAY JAAAY - 3 months ago 38
Android Question

Android: "Method is never used" warning for onClick method

This is a part of my calc_fragment.xml file ,

<Button
android:id="@+id/b7"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_margin="2dp"
android:background="@drawable/roundedbutton"
android:fontFamily="sans-serif-thin"
android:text="Add"
android:textColor="@color/light_grey"
android:textSize="45sp"
android:onClick="clicked"/>


that is linked with the following fragment:

public class CalcFragment extends Fragment {

private TextView textView;
private String text;
private Vibrator vibe;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.calc_fragment, container, false);
return rootView;
}

public void clicked (View v){ <--- "Method clicked is never used"
...content...
}


I get a warning "Method clicked is never used" but I my button is linked with this method

Answer

In the onCreateView method of the CalcFragment, you need to declare and initialize the button after the initializing the rootView:

Button b7 = (Button) rootView.findViewById(R.id.b7);

You then need an onClickListener instead of defining your own clicked method. There are two methods to listen to a click of a button.

The first method:

You can set the onClickListener within the onCreatView as follows:

b7.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
       // Do something         
    }
});   

The second method:

You can define an onClickListener as follows:

final View.OnClickListener b7OnClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        // Do something
    }
};

When using the second method, you will need to set the onClickListener like you did in the first method however in this case you will pass the name of the onClickListener object you created.

Example:

b7.setOnClickListener(b7OnClickListener);