【问题标题】:OnClick doesn't fire in custom Button class but in parent classOnClick 不会在自定义 Button 类中触发,而是在父类中触发
【发布时间】:2011-04-21 15:16:41
【问题描述】:

我创建了自己的按钮

<merge xmlns:android="http://schemas.android.com/apk/res/android">
    <ImageView
        ...></ImageView>

    <ImageView
        ...></ImageView>

    <TextView
        ...></TextView>
</merge>

她是我的 Button 的类

public class StandardButton extends RelativeLayout implements OnClickListener{
    ...

private void init(Context context){
        this.setClickable(true);
        this.setEnabled(true);
        this.setFocusable(true);
        this.setFocusableInTouchMode(true);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.standard_button, this);

    }

    @Override
        public void onClick(View v) {
            setLabel("Click");
        }

onClick 功能不起作用。但是,如果我将 Button 放在我的 Activity 中并覆盖 onClick 函数,它会起作用。

在我的 StandardButton 类中单击 Button 时是否有触发函数的解决方案。这个类应该知道它是否被点击,而不是活动!

【问题讨论】:

  • 了解您想要实现的目标或更直接地了解为什么常规的 Android 按钮实现也不能满足您的需求可能会有所帮助。实验/学习是一个完全可以接受的答案。 :)
  • 您可以很容易地看到好处。标准 Button 没有 2 个 Imageview 和 1 个 Textview。

标签: android button onclick parent-child


【解决方案1】:
this.setOnClickListener(this);

init() 方法应该可以解决问题。

【讨论】:

    【解决方案2】:
    this.setFocusableInTouchMode(true);
    
    this.setFocusable(true);
    

    在您的 onclick 事件中出现的这两行错误将其删除并

    放它

    this.setFocusable(false);
    

    onclick 将起作用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-05
      • 2020-08-11
      相关资源
      最近更新 更多