0

I have a custom View, a Button, but setOnClickListener() does not work.

class ButtonReadBarcode extends android.support.v7.widget.AppCompatButton {

    public String ma_vach = "";
    private Activity ac = null;

    public ButtonReadBarcode(Context context) {
        super(context);
        ac = Global.getActivity( context);
        init();
    }
    private void init(){
        setVisibility(View.VISIBLE);
        setLayoutParams( new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        setText("Scan barcode ...");
        setAllCaps(false);
    }

    @Override
    public void setOnClickListener( View.OnClickListener l) {
        super.setOnClickListener(l);
        // this line does now work        
        setText("I want this text show when click");
    }

}

not any error messages

Fareanor
  • 5,900
  • 2
  • 11
  • 37
quanlevan
  • 33
  • 6

2 Answers2

2

You are overriding your setOnClickListener, it will only work if you call it somewhere else, then it will do what you pass as parameter+set the text as you wrote.

To override the basic click of the button you should override onClick:

@Override
public void onClick(View v) {
     setText("I want this text show when click");
}
Ricardo A.
  • 685
  • 2
  • 8
  • 35
0

For this problem you can try the following code it is working for me:

public class CustomButton extends AppCompatButton {
    public CustomButton(Context context) {
        super(context);
    }

    public CustomButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setOnClickListener(@Nullable OnClickListener l) {
        super.setOnClickListener(l);
        setText("asdf");
    }
}

Here is the XML:

<com.example.stackoverflowquestions.CustomButton
            android:id="@+id/customButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#FFFFFF"
            android:text="Custom Button"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            android:background="@color/colorPrimaryDark"/>

And simply use it in MainActivity as:

 CustomButton customButton =  findViewById(R.id.customButton);
        customButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
  • That will work, but setting an empty onClickListener is a unnecessary workaround, it's better and simpler to just override onClick. – Ricardo A. Oct 29 '19 at 17:16