3

I have a custom view MyView inflated from my_view.xml (with a corresponding Java class MyView.java).

I override MyView(Context context, AttributeSet attrs) to connect subviews up to members of the class.

Now one of these subviews is a Button, and I'd like for my view to listen for a click on its button before passing this event on to a delegate. However if I declare

this.myButton.setOnClickListener(this);

in the constructor MyView(Context context, AttributeSet attrs) (where this is an instance of MyView) I get a NullPointerException.

Where is an appropriate place in MyClass.java to call this.myButton.setOnClickListener(this);?

%%

Edit. Some code:

public MyView(Context ctx, AttributeSet attrs)
{
  super(context, attrs);
  this.myButton = (Button) this.findViewById(R.id.my_button);
  this.myButton.setOnClickListener(this); // Raises null pointer;'id' is correct.
}
4

2 回答 2

2

不要尝试setOnClickListener(this)在构造函数中进行调用,而是在按钮完全初始化后进行。尝试移动setOnClickListener(this),以便从父活动的onResume方法(间接)调用它,如下所示:

public class MainMenuActivity extends Activity {
    @Override
    public void onResume() {
        super.onResume();
        new MyView(this, attrs).onResume();
    }
   ...
}

public class MyView {
    public void onResume() {
        myButton.setOnClickListener(this);
    }
  ...
}

我一直使用Roboguice 来做这类事情,强烈推荐它。我的按钮处理程序代码如下所示:

class ButtonHandler implements OnClickListener {
    @InjectView(R.id.MainMenuButton)
    private Button button;

    public void onResumeEvent( @Observes OnResumeEvent onResume ) {
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        doSomethingUseful();
    }
}
于 2011-08-27T03:49:57.700 回答
0

问题是我错过了构造函数中的膨胀:

LayoutInflater i = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
i.inflate(R.layout.my_view, this);

这让我感到困惑,因为我认为构造函数MyView(Context ctx, AttributeSet attrs)会在膨胀视图时被调用,而不是相反。

于 2011-08-27T04:16:53.543 回答