Button不会在onClickListener中初始化

时间:2014-11-06 00:29:20

标签: android button onclicklistener

我正在尝试通过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);    
                    }
                }

1 个答案:

答案 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}}

  

返回运行视图的上下文,通过它可以访问当前主题,资源等。