【问题标题】:Set onClickListener in an Android custom view在 Android 自定义视图中设置 onClickListener
【发布时间】:2018-09-12 09:53:13
【问题描述】:

我正在尝试为按钮构建简单的库, 在我在类下面创建的库文件夹中

 public class SimpleImageButton extends AppCompatImageView implements AppCompatImageView.OnClickListener{

    public Context mContext;
    Activity activity;

    public SimpleImageButton (Context context) {
        super(context);
        mContext = context;
        setCustomTypeface(context, null);

    }

    public SimpleImageButton (Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        setCustomTypeface(context, attrs);

    }

    public SimpleImageButton (Context context, AttributeSet attrs, int defStyleAttr) 
    {
        super(context, attrs, defStyleAttr);
        mContext = context;
        setCustomTypeface(context, attrs);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void setCustomTypeface(Context context, AttributeSet attrs)  {
        if(isInEditMode())
            return;
        TypedArray a = context.obtainStyledAttributes(attrs, 
        android.support.v7.appcompat.R.styleable.TextAppearance);
        setBackground(ContextCompat.getDrawable(mContext, 
    R.drawable.applogo_ads));
        a.recycle();

    }
   public void onClick(View view) {
        // here i have some functions to execute
    }
}

和我在 App 文件夹中的 Mainclass

   SimpleImageButton imgBtn= (SimpleImageButton )findViewById(R.id.clickButton);

imgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               imgBtn.onClick(view);
              // without this line how can i reach to onclick() of simpleImageButton class
            }
        });

所以当我单击按钮时它会正常工作。但我想让库按钮直接工作,在主活动中没有 onClick 函数,点击按钮应该直接重定向到 SimpleImageButton 类的 onclcik 方法

我对堆栈溢出非常陌生,如果语法/提问方式有任何错误,请不要介意。 谢谢。

【问题讨论】:

  • 在你的库中使用回调监听器..监听器的 onClick 只是将回调发送回父活动或片段
  • 我想实现一些事情,比如我不应该在主要活动中为点击操作写任何东西!!!!!! onclicking 该按钮应该直接执行 SimpleImageButton 类 onclick() 方法中存在的功能

标签: android android-studio android-button android-library


【解决方案1】:

在视图的构造函数中使用 setOnClickListener(this)。

public SimpleImageButton (Context context) {
        super(context);
        mContext = context;
        setCustomTypeface(context, null);
        setOnClickListener(this);
    }

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多