按下按钮创建CheckBox

时间:2015-06-29 18:09:43

标签: java android checkbox

我正在尝试创建一个复选框,当单击一个按钮时,但我总是收到此错误:

Error:(30, 52) error: incompatible types: <anonymous OnClickListener> cannot be converted to Context

这是产生错误的代码:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button myButton = (Button) findViewById(R.id.myButton);

    myButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            LinearLayout myLayout = (LinearLayout) findViewById(R.id.myLayout);

            CheckBox myCheckBox = new CheckBox(this);
            myCheckBox.setLayoutParams(new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.FILL_PARENT,
                    LinearLayout.LayoutParams.FILL_PARENT));

            myLayout.addView(myCheckBox);
        }
    });

}

导致不兼容类型的原因是什么?

1 个答案:

答案 0 :(得分:0)

它无法正常工作,因为您将上下文作为View.OnClickListener传递。改变

new CheckBox(this)

到:

new CheckBox(v.getContext());