【问题标题】:setOnClickListener() does not work in my custom ViewsetOnClickListener() 在我的自定义视图中不起作用
【发布时间】:2019-10-29 23:48:51
【问题描述】:

我有一个自定义视图,一个按钮,但 setOnClickListener() 不起作用。

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");
    }

}

没有任何错误信息

【问题讨论】:

标签: android onclicklistener android-custom-view


【解决方案1】:

您正在覆盖您的 setOnClickListener,它只有在您在其他地方调用它时才会起作用,然后它会执行您作为参数传递的操作 + 设置您编写的文本。

要覆盖按钮的基本点击,您应该覆盖 onClick:

@Override
public void onClick(View v) {
     setText("I want this text show when click");
}

【讨论】:

    【解决方案2】:

    对于这个问题,你可以试试下面对我有用的代码:

    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");
        }
    }
    

    这是 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"/>
    

    并在 MainActivity 中简单地使用它:

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

    【讨论】:

    • 这会起作用,但是设置一个空的 onClickListener 是不必要的解决方法,只覆盖 onClick 会更好更简单。
    猜你喜欢
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-28
    相关资源
    最近更新 更多