我正在尝试通过Button
动态添加OnClickListener
。但我一直在行中出错
Button myButton = new Button(this);
错误说
The constructor Button(new View.OnClickListener(){}) is undefined
那么,如果它不能让我初始化它,我该怎么创建这个Button
呢?有没有更好的方法来设置OnClickListener
?
button_test.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
LinearLayout ll = (LinearLayout)findViewById(R.id.ll_bttn_words);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
Button myButton = new Button(this); //error
myButton.setText("Add Me");
ll.addView(myButton, lp);
}
}
答案 0 :(得分:2)
更改
Button myButton = new Button(this);
到
Button myButton = new Button(view.getContext());
此处,this
引用OnClickListener
因此错误消息。您想要的是Activity Context
view
onClick()
中的参数Context
将返回的getContext()
。
From the docs {{1}}
返回运行视图的上下文,通过它可以访问当前主题,资源等。