<togglebutton> onClickListener - 创建和删除按钮?</togglebutton>

时间:2012-02-10 18:44:09

标签: java android button togglebutton

是否可以在切换onClickListener时创建和删除按钮?

目前我的代码如下:

    Button minuskegle, minuskugle, pluskugle, pluskegle, plusmidkegle, minusmidkegle;
ToggleButton toggle;


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    toggle = (ToggleButton) findViewById(R.id.bRedGreen);
    toggle.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            pluskugle = (Button) findViewById(R.id.bBallhole);
            minuskugle = (Button) findViewById(R.id.bBallhole);

            pluskegle = (Button) findViewById(R.id.bKegle);
            minuskegle = (Button) findViewById(R.id.bKegle);

            plusmidkegle = (Button) findViewById(R.id.bKeglemid);
            minusmidkegle = (Button) findViewById(R.id.bKeglemid);

        if(toggle.isChecked())
        {
            minuskugle.setBackgroundResource(R.drawable.redballinhole);
            minuskegle.setBackgroundResource(R.drawable.redkegle);
            minusmidkegle.setBackgroundResource(R.drawable.midkegleminus);
        }

        else 
        {
            pluskugle.setBackgroundResource(R.drawable.whiteballinhole);
            pluskegle.setBackgroundResource(R.drawable.kegleb);
            plusmidkegle.setBackgroundResource(R.drawable.midkegleplus);
        }

        }

    });
}

我需要它在if(toggle.isChecked())

上创建按钮

否则

删除它们

1 个答案:

答案 0 :(得分:0)

足够容易了:)

找到要在其中插入新按钮的父视图,创建按钮,在视图中插入按钮:

RelativeLayout parentView = (RelativeLayout) findViewById(R.id.parentView);
Button buttonTest = new Button(MyActivity.this);
parentView.addView(buttonTest);

MyActivity.this是必要的,因为你在click函数里面,这并不是指活动。